简体   繁体   中英

Storing weak references in NSMutableDictionary

I'm implementing a cache,wherein I use NSMutableDictionary to store weak reference of objects.I know NSMaptable provides an efficient way to store weak and strong refereces.But its available on >=iOS6. My requirement is to support iOS>=5.Is there a better way then using NSMutableDicitonary? .Any code snippets for storing weak reference in NSMutableDictionary ,would help.And also,Can i use NSCache for this case?Thanks.

Here is my category for weak references NSMutableDictionary.

.h file:

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

.m file:

#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

How to use:

Replace with your [dic setObject:obj forKey:key]; with [dic setWeakReferenceObj:obj forKey:key];

Note:

Because dealloc objects are cached in dictionary, if your weak reference dic is global used, you should invoke [dic removeDeallocRef]; at some proper position, like - (void)didReceiveMemoryWarning{} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM