我有一个类,它充当NSMutableDictionary的子类(主要是通过委托),因为我们有一些封装在字典周围的自定义接口。当运行ios泄漏工具时,它将我的keyEnumerator方法标识为NSFastEnumerationEnumerator对象泄漏的来源。
下面是我的keyEnumeration方法,它是包装的NSMutableDictionary的委托。
- (NSEnumerator*) keyEnumerator {
return [dictionary keyEnumerator];
}泄漏的回溯始终将枚举器显示为源:
- (void) someMethod {
for (NSString *key in myWrappedDictionary) { ... }
}下面是一个典型的回溯:
calloc
class_createInstance
__CFAllocateObject2
-[__NSCFDictionary keyEnumerator]
-[WrappedDictionary keyEnumerator]
-[NSDictionary countByEnumerating...
-[SomeClass someMethod]我正在寻找我的一行代码中的变通方法或缺陷。我用的是ARC。
下面显示了一个示例类。调用WrappedDictionary createLeaks将产生9个泄漏。
@interface WrappedDictionary : NSMutableDictionary {
NSMutableDictionary *dictionary;
}
- (id) init;
- (NSUInteger) count;
- (NSEnumerator*) keyEnumerator;
- (void)setObject:(id)anObject forKey:(id)key;
@end
@implementation WrappedDictionary
- (id) init {
dictionary = [NSMutableDictionary new];
return self;
}
- (NSUInteger) count { return [dictionary count]; }
- (NSEnumerator*) keyEnumerator {
return [dictionary keyEnumerator];
}
- (void)setObject: anObject forKey:key {
[dictionary setObject:anObject forKey: key];
}
+ (void) createLeaks {
for (int i=0; i < 10; i++) {
WrappedDictionary *dict = [WrappedDictionary new];
[dict setObject:@"1" forKey:@"1"];
[dict setObject:@"2" forKey:@"2"];
[dict setObject:@"3" forKey:@"3"];
for (NSString *key in dict) {
NSLog(@"key=%@",key);
}
}
}
@end发布于 2012-03-21 08:44:48
请记住,泄漏工具仅显示泄漏内存的分配位置。这并不意味着分配点是泄漏的来源。更有可能的泄漏来源是在someMethod中,或者在someMethod的调用者中,特别是如果你把它放到一个ivar中,然后在整个对象上有一个保留周期。
发布于 2012-03-22 23:31:09
我发现了一个简单的解决方法。
如果我将keyEnumerator方法从
- (NSEnumerator*) keyEnumerator {
return [dictionary keyEnumerator];
}至
- (NSEnumerator*) keyEnumerator {
NSEnumerator *e = [dictionary keyEnumerator];
return e;
}泄漏就会消失。这对我来说仍然没有意义,但它显然迫使编译器正确地ARC从字典返回。
https://stackoverflow.com/questions/9795683
复制相似问题