iOS开发基础知识

使用 GCD 进行多读单写

2019-02-26  本文已影响0人  永远保持一颗进取心
#import "WHObject.h"

@interface WHObject()

@property (nonatomic, strong) dispatch_queue_t dictQueue;//并发队列
@property (nonatomic, strong) NSMutableDictionary *dict;//可变字典

@end

@implementation WHObject

- (instancetype)init {
    if(self = [super init]) {
        _dictQueue = dispatch_queue_create("com.huangwenhong.queue", DISPATCH_QUEUE_CONCURRENT);
        _dict = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)huangwenhongmethod {
    self.target = [NSObject new];
}

- (id)valueForKey:(NSString *)key {
    id __block obj;
    dispatch_sync(_dictQueue, ^{//因为有数据 return,所以这里是同步调用
        obj = [self.dict valueForKey:key];
    });
    return obj;
}

- (void)setObject:(id)obj forKey:(id<NSCopying>)key {
    //重点:dispatch_barrier_async(),异步栅栏调用;
    //只有提交到并行队列才有意义
    dispatch_barrier_async(_dictQueue, ^{
        [self.dict setObject:obj forKey:key];
    });
}




@end


上一篇下一篇

猜你喜欢

热点阅读