max*_*eis 0 iphone xcode memory-leaks analyzer
使用以下代码,分析器将setMyDict选择器调用标记为潜在泄漏,并且在dealloc中指出"调用者此时不拥有引用计数的不正确减少"
- (id)init {
if (self = [super init]) {
[self setMyDict:[[NSMutableDictionary alloc] init]];
}
return self;
}
- (void)dealloc {
[[self myDict] release];
[super dealloc];
}
@synthesize myDict = _myDict;
Run Code Online (Sandbox Code Playgroud)
我不明白.我想,使用alloc init,对象会将保留计数增加1,指针会通过合成属性存储在_myDict中.如果我使用此代码
- (id)init {
if (self = [super init]) {
_myDict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)dealloc {
[_myDict release];
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)
分析师不抱怨.我错过了什么?
@synthesize为您正在合成的对象提供了setter和getter.
setter方法看起来像这样(取自Apple文档)
-(void)setMyDict:(NSMutableDictionary *)newDict {
if (myDict != newDict) {
[myDict release];
myDict = [newDict retain];
}
}
Run Code Online (Sandbox Code Playgroud)
当你这样做时,你会造成泄漏:
[self setMyDict:[[NSMutableDictionary alloc] init]];
Run Code Online (Sandbox Code Playgroud)
因为你永远不会发布新分配的字典.
解决这个问题的方法是:
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[self setMyDict:dict];
[dict release];
Run Code Online (Sandbox Code Playgroud)
这可以解决泄漏问题.
在dealloc方法中,您应该使用:
[myDict release]; // Or whatever your property is called.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2556 次 |
最近记录: |