我对使用 NSMutableDictionary
时的线程安全有疑问。
主线程正在从 NSMutableDictionary
读取数据,其中:
NSString
UIImage
一个异步线程正在向上面的字典写入数据(使用NSOperationQueue
)
如何使上述字典线程安全?
我应该将 NSMutableDictionary
属性设为 atomic
吗?还是我需要进行任何其他更改?
@property(retain) NSMutableDictionary *dicNamesWithPhotos;
最佳答案
NSMutableDictionary
并非设计为线程安全的数据结构,只是将属性标记为 atomic
,并不能确保实际执行底层数据操作原子地(以安全的方式)。
为确保每个操作都以安全的方式完成,您需要用锁保护字典上的每个操作:
// in initialization
self.dictionary = [[NSMutableDictionary alloc] init];
// create a lock object for the dictionary
self.dictionary_lock = [[NSLock alloc] init];
// at every access or modification:
[object.dictionary_lock lock];
[object.dictionary setObject:image forKey:name];
[object.dictionary_lock unlock];
您应该考虑滚动您自己的 NSDictionary
,它只是在持有锁的同时将调用委托(delegate)给 NSMutableDictionary:
@interface SafeMutableDictionary : NSMutableDictionary
{
NSLock *lock;
NSMutableDictionary *underlyingDictionary;
}
@end
@implementation SafeMutableDictionary
- (id)init
{
if (self = [super init]) {
lock = [[NSLock alloc] init];
underlyingDictionary = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void) dealloc
{
[lock_ release];
[underlyingDictionary release];
[super dealloc];
}
// forward all the calls with the lock held
- (retval_t) forward: (SEL) sel : (arglist_t) args
{
[lock lock];
@try {
return [underlyingDictionary performv:sel : args];
}
@finally {
[lock unlock];
}
}
@end
请注意,因为每个操作都需要等待锁并持有它,所以它的可扩展性不是很好,但在您的情况下可能已经足够了。
如果你想使用合适的线程库,你可以使用 TransactionKit library因为他们有 TKMutableDictionary
这是一个多线程安全库。我个人没用过,看来是个正在开发中的库,你不妨试试看。
https://stackoverflow.com/questions/1986736/
相关文章:
objective-c - 在 Objective-C 中定义协议(protocol)的类别?
iphone - 更改 UIAlertView 的背景颜色?
objective-c - 滚动 NSScrollView 时的回调?
iphone - 如何在我的 Objective-C 源代码中转义 Unicode 字符?
ios - swift 中的@property/@synthesize 等价物
ios - 静态和动态单元格的 UITableView 混合?
iphone - 如何以编程方式创建 UIScrollView?