iOS 多线程安全 与 可变字典
//
//
// banggood
//
// Created by Artillery on 2017/10/16.
// Copyright © 2017年 banggood. All rights reserved.
//
#import <Foundation/>
/*
多线程下的安全字典 来自阿里
*/
@interface SyncMutableDictionary : NSObject
- (nullable id)objectForKey:(_Nonnull id)aKey;
- (nullable id)valueForKey:(_Nonnull id)aKey;
- (NSArray * _Nonnull)allKeys;
- (void)setObject:(nullable id)anObject forKey:(_Nonnull id <NSCopying>)aKey;
- (void)removeObjectForKey:(_Nonnull id)aKey;
- (void)removeAllObjects;
- (NSMutableDictionary *_Nonnull)getDictionary;
@end
//
//
// banggood
//
// Created by Artillery on 2017/10/16.
// Copyright © 2017年 banggood. All rights reserved.
//
#import ""
@interface SyncMutableDictionary ()
@property(nonatomic, strong) NSMutableDictionary *dictionary;
@property(nonatomic, strong) dispatch_queue_t dispatchQueue;
@end
@implementation SyncMutableDictionary
- (instancetype)init {
if (self = [super init]) {
_dictionary = [NSMutableDictionary new];
_dispatchQueue = dispatch_queue_create("", DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (NSArray * _Nonnull)allKeys{
__block NSArray *allKeys = [NSArray array];
dispatch_sync(_dispatchQueue, ^{
allKeys = [_dictionary allKeys];
});
return allKeys;
}
- (nullable id)objectForKey:(_Nonnull id)aKey{
__block id returnObject = nil;
if(!aKey) return returnObject;
dispatch_sync(_dispatchQueue, ^{
returnObject = _dictionary[aKey];
});
return returnObject;
}
- (void)setValue:(nullable id)value forKey:(NSString *)key {
if(!key) return;
dispatch_barrier_async(_dispatchQueue, ^{
[_dictionary setValue:value forKey:key];
});
}
- (nullable id)valueForKey:(_Nonnull id)aKey{
__block id returnObject = nil;
dispatch_sync(_dispatchQueue, ^{
returnObject = [_dictionary valueForKey:aKey];
});
return returnObject;
}
- (void)setObject:(nullable id)anObject forKey:(_Nonnull id <NSCopying>)aKey{
dispatch_barrier_async(_dispatchQueue, ^{
if (anObject == nil) return;
[aKey] = anObject;
});
}
- (void)removeObjectForKey:(_Nonnull id)aKey{
if(!aKey) return;
dispatch_sync(_dispatchQueue, ^{
[_dictionary removeObjectForKey:aKey];
});
}
- (void)removeAllObjects {
dispatch_sync(_dispatchQueue, ^{
[_dictionary removeAllObjects];
});
}
- (NSMutableDictionary *)getDictionary {
__block NSMutableDictionary *temp;
dispatch_sync(_dispatchQueue, ^{
temp = _dictionary;
});
return temp;
}
-(NSString *)description{
return [NSString stringWithFormat:@"%@",];
}
@end