分析标记这个结构潜在的泄漏
-
25-09-2019 - |
题
使用以下代码分析器痕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;
我不明白这一点。我认为,与所述ALLOC初始化对象增加了由一个保留计数和将指针通过合成属性存储在_myDict。如果我使用这个代码,而不是
- (id)init {
if (self = [super init]) {
_myDict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)dealloc {
[_myDict release];
[super dealloc];
}
分析器不抱怨。我缺少什么?
解决方案
在@synthesize提供了一个setter和getter为对象你合成
一个setter方法看起来是这样的(从Apple文档截取)
-(void)setMyDict:(NSMutableDictionary *)newDict {
if (myDict != newDict) {
[myDict release];
myDict = [newDict retain];
}
}
您正在创建一个泄漏,当你做的:
[self setMyDict:[[NSMutableDictionary alloc] init]];
由于你永远不会释放新alloc'd字典。
一个方式来解决此是:
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[self setMyDict:dict];
[dict release];
这取泄漏的照顾。
在dealloc方法,应使用:
[myDict release]; // Or whatever your property is called.
不隶属于 StackOverflow