0

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.

Karthik207
  • 493
  • 9
  • 27

1 Answers1

0

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{}.

simalone
  • 2,768
  • 1
  • 15
  • 20