一:HPCache
一個(gè)簡單的線程安全且高吞吐量的模型,用于存儲簡單數(shù)據(jù)串纺,支持model存儲俭茧,無需轉(zhuǎn)換。
二:思路
- 創(chuàng)業(yè)一個(gè)自定義的DISPATCH_QUEUE_CONCURRENT隊(duì)列忱屑。
- 將dispatch_sync(或dispatch_async)用于不修改狀態(tài)的操作。
- 將dispatch_barrier_sync(或dispatch_barrier_async)用于可能修改狀態(tài)的操作暇昂。
注意:這里的屬性被標(biāo)記為nonatomic莺戒,因?yàn)檫@里有自定義的代碼使用了自定義的隊(duì)列和屏障來管理線程安全。
三:代碼
#import <Foundation/Foundation.h>
@interface HPCache : NSObject
+ (HPCache *)sharedInstance;
- (id)objectForKey:(nonnull id<NSCopying>)key;
- (void)setObject:(id)object forKey:(nonnull id<NSCopying>)Key;
- (void)removeObjectForKey:(nonnull id<NSCopying>)Key;
@end
#import "HPCache.h"
@interface HPCache()
@property (nonatomic, readonly) NSMutableDictionary *cacheObjects;
@property (nonatomic, readonly) dispatch_queue_t queue;
@end
@implementation HPCache
const char *_Nullable kCacheQueueName = "kCacheQueueName";
- (instancetype)init{
if (self = [super init]) {
_cacheObjects = [NSMutableDictionary dictionary];
_queue = dispatch_queue_create(kCacheQueueName, DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
+ (HPCache *)sharedInstance{
static HPCache *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[HPCache alloc] init];
});
return instance;
}
- (id)objectForKey:(id<NSCopying>)key{
__block id rv = nil;
dispatch_sync(self.queue, ^{
rv = [self.cacheObjects objectForKey:key];
});
return rv;
}
- (void)setObject:(id)object forKey:(id<NSCopying>)Key{
dispatch_barrier_sync(self.queue, ^{
[self.cacheObjects setObject:object forKey:Key];
});
}
- (void)removeObjectForKey:(nonnull id<NSCopying>)Key{
dispatch_barrier_sync(self.queue, ^{
[self.cacheObjects removeObjectForKey:Key];
});
}
@end
附上Demo