延迟加载和线程安全字典

时间:2015-06-04 13:24:46

标签: objective-c thread-safety lazy-loading grand-central-dispatch nsmutabledictionary

我经常使用这种模式:

@property (nonatomic, readwrite, strong) NSMutableDictionary * mutableDictionary;

[...]

- (id)objectForKey:(NSString *)key
{
    id result = self.mutableDictionary[key];

    if (!result)
    {
        result = [...] ; // go and fetch the result;

        self.mutableDictionary[key] = result;
    }

    return result ;
}

但我最近意识到它不是线程安全的。我想有一个类似的延迟加载模式,但它是线程安全的。

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我会使用NSLock对象。它们易于使用。只需将mutabledictionary的setter包装在其中。

@property (nonatomic, readwrite, strong) NSMutableDictionary * mutableDictionary;

NSLock *mutexLock = [NSLock new];
[...]

- (id)objectForKey:(NSString *)key
{
    id result = self.mutableDictionary[key];

    if (!result)
    {
        [mutexLock lock];
        result = [...] ; // go and fetch the result;
        self.mutableDictionary[key] = result;
        [mutexLock unlock];
    }

    return result ;
}

更新:这假设//go fetch results中的所有内容都不是线程安全的。