NSMutableDictionary
不是线程安全的数据 struct ,仅仅将属性标记为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
,简单地将调用委托给NSMutable字典,同时保持锁:
@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
请注意,因 for each 操作都需要等待锁并保持它,所以它的可扩展性不强,但在您的情况下可能已经足够好了.
如果你想使用一个合适的线程库,你可以使用TransactionKit library,因为他们有TKMutableDictionary
,这是一个多线程的安全库.我个人还没有使用过它,而且它似乎是一个正在开发的库,但您可能想try 一下.