iOS 设计一个多读单写的小功能

话不多说直接撸代码

.h文件

#import 

NS_ASSUME_NONNULL_BEGIN

@interface QJMultireadSIngleRead : NSObject

@end

NS_ASSUME_NONNULL_END

.m文件

#import "QJMultireadSIngleRead.h"

@interface QJMultireadSIngleRead() {
//    并发队列
    dispatch_queue_t concurrent_queue;
}
//    容器

@property (nonatomic, strong) NSMutableDictionary *muDict;
@end

@implementation QJMultireadSIngleRead

- (instancetype)init {
    if (self = [super init]) {
        //创建一个并发队列
        concurrent_queue = dispatch_queue_create("mutliread_single_read", DISPATCH_QUEUE_CONCURRENT);
        //创建字典
        _muDict = [NSMutableDictionary dictionary];
    }
    return self;
}

- (id)objectForKey:(NSString *)key {
    __block id obj;
    __weak __typeof(self)weakSelf = self;
    dispatch_async(concurrent_queue, ^{
        obj = [weakSelf.muDict objectForKey:key];
    });
    return self;;
}

- (void)setObject:(id)object forKey:(NSString *)key {
    __weak __typeof(self)weakSelf = self;
//    异步栅栏调用设置数据
    dispatch_barrier_sync(concurrent_queue, ^{
        [weakSelf.muDict setObject:object forKey:key];
    });
}
@end

你可能感兴趣的:(iOS 设计一个多读单写的小功能)