這裏是我的類別弱引用的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{}
。