在NSMutableDictionary中存储弱引用

时间:2014-02-10 05:35:43

标签: ios caching nsmutabledictionary weak-references nscache

我正在实现一个缓存,其中我使用NSMutableDictionary来存储对象的弱引用。我知道NSMaptable提供了一种存储弱和强引用的有效方法。但它可用于> = iOS6的。我的要求是支持iOS> = 5.有更好的方法然后使用NSMutableDicitonary?。任何代码片段用于在NSMutableDictionary中存储弱引用,会有所帮助。而且,我可以在这种情况下使用NSCache吗? ?谢谢。

1 个答案:

答案 0 :(得分:0)

这是弱引用NSMutableDictionary的类别。

.h文件:

@interface NSMutableDictionary (WeakReferenceObj)
- (void)setWeakReferenceObj:(id)obj forKey:(NSString *)key;
- (void)removeDeallocRef;
@end

.m文件:

#pragma mark - WeakReferenceObj
@interface WeakReferenceObj : NSObject
@property (nonatomic, weak) id weakRef;
@end

@implementation WeakReferenceObj
+ (id)weakReferenceWithObj:(id)obj{
    WeakReferenceObj *weakObj = [[WeakReferenceObj alloc] init];
    weakObj.weakRef = obj;
    return weakObj;
}
@end

#pragma mark - NSMutableDictionary(WeakReferenceObj)
@implementation NSMutableDictionary(WeakReferenceObj)

- (void)setWeakReferenceObj:(id)obj forKey:(NSString *)key{
    [self setObject:[WeakReferenceObj weakReferenceWithObj:obj] forKey:key];
}

- (void)removeDeallocRef{
    NSMutableArray *deallocKeys = nil;
    for (WeakReferenceObj *weakRefObj in [self allKeys]) {
        if (!weakRefObj.weakRef) {
            if (!deallocKeys) {
                deallocKeys = [NSMutableArray array];
            }
            [deallocKeys addObject:weakRefObj];
        }
    }
    if (deallocKeys) {
        [self removeObjectsForKeys:deallocKeys];
    }

}

@end

使用方法:

替换你的 [dic setObject:obj forKey:key];[dic setWeakReferenceObj:obj forKey:key];

。{

注意:

因为dealloc对象被缓存在字典中,如果你的弱引用dic是全局使用的,你应该在某个适当的位置调用[dic removeDeallocRef];,如- (void)didReceiveMemoryWarning{}