2014-02-10 58 views
0

我正在實現一個緩存,其中我使用NSMutableDictionary來存儲對象的弱引用。我知道NSMaptable提供了一種有效的方法來存儲弱和強引用。但其可用於> = iOS6。我的要求是支持的iOS> = 5.Is有那麼使用NSMutableDicitonary?。任何代碼段爲NSMutableDictionary存儲弱引用,將help.And還,我可以用NSCache這種情況下的更好的辦法?謝謝。在NSMutableDictionary中存儲弱引用

回答

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