编译器说有内存泄漏,但我没有看到

时间:2011-09-21 02:24:41

标签: iphone objective-c xcode memory-management memory-leaks

所以我用Xcode做了那个你说分析的东西,它找到了漏洞和东西,在这里,它说我漏了(在下面的代码中标出)。

// Copy dictionary to memory
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"DataCategoriesDictionary" ofType:@"plist"];
NSDictionary *dataCategoriesDictionary = [[NSDictionary alloc] initWithContentsOfFile:filepath];
self.choices = [[NSMutableDictionary alloc] initWithDictionary:[dataCategoriesDictionary objectForKey:self.chosenCategory]]; // LINE 55
[dataCategoriesDictionary release]; // HERE, the compiler says "Potential leak of an object allocated on line 55"

即使我没有任何意义可以泄漏实例变量,但我还是尝试为它添加一个发布语句,Xcode仍然给了我同样的错误。还有什么我可以泄漏?

3 个答案:

答案 0 :(得分:5)

如果选项是带保留的属性,则会泄漏NSMutableDictionary。

[[NSMutableDictionary alloc] initWithDictionary

自动释放或使用临时。

self.choices = [[[NSMutableDictionary alloc] initWithDictionary:[dataCategoriesDictionary objectForKey:self.chosenCategory]] autorelease];

或(我最喜欢的)

self.choices = [NSMutableDictionary dictionaryWithDictionary:[dataCategoriesDictionary objectForKey:self.chosenCategory];

NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:[dataCategoriesDictionary objectForKey:self.chosenCategory]];
self.choices = tempDict;
[tempDict release];

答案 1 :(得分:1)

choices看起来像Declared Property。看来你已经宣布如下:

在.h文件中:
@property (nonatomic, retain) NSMutableDictionary *choices;

在.m文件中:
@synthesize choices

在这种情况下,编译器会自动提供setter方法:

-(void) setChoices:(NSMutableDictionary*)newValue
{
    if (choices != newValue) {
        [choices release];
        choices = [newValue retain];
    }
}

从您的代码中,self.choices隐式调用setChoices方法。所以新分配的NSMutableDictionary的保留计数变为2而不是1,导致对象泄漏。

答案 2 :(得分:-2)

您应该释放属性choice引用的成员变量(ivar)。所以假设有一个成员变量_choice,然后像这样释放它:

[_choice release]

应该有用。

或者,如果你像这样重写它,可能会更清楚为什么会有泄漏:

NSMutableDictionary * temp = [[NSMutableDictionary alloc] initWithDictionary:[dataCategoriesDictionary 
self.choices = temp
[temp release]