美文网首页
iOS 设计一个多读单写的小功能

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

作者: Q14 | 来源:发表于2020-05-24 00:03 被阅读0次

话不多说直接撸代码

.h文件

#import <Foundation/Foundation.h>

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 设计一个多读单写的小功能

      本文链接:https://www.haomeiwen.com/subject/uwgrahtx.html