编译器说存在内存泄漏,但我没有看到内存泄漏
所以我用 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 仍然给了我同样的错误。我还能泄露什么?
So I did that thing with Xcode where you say analyze and it finds leaks and stuff and here, it says that I am leaking (marked in code below).
// 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"
Even though it doesn't make any sense that I could be leaking a instance variable, I tried adding a release statement for it anyway and Xcode still gave me the same error. What else could I be leaking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果选择是带有保留的属性,那么您就会泄漏 NSMutableDictionary。
自动释放或使用临时的。
或(我最喜欢的)
或
If choices is a property with retain you are leaking the NSMutableDictionary.
Either autorelease or use a temporary.
or (my favorite)
or
choices
看起来像 声明的财产。看来你是这样声明的:在 .h 文件中:
@property(非原子,保留)NSMutableDictionary *choices;
在 .m 文件中:
@synthesize choice
在这种情况下,编译器会自动提供 setter 方法:
在您的代码中,
self.choices
隐式调用 setChoices 方法。所以新分配的 NSMutableDictionary 的保留计数变成 2 而不是 1,导致对象泄漏。choices
looks like a Declared Property. It seems that you'd declared it like below:In .h file:
@property (nonatomic, retain) NSMutableDictionary *choices;
In .m file:
@synthesize choices
In this case, the compiler automatically provides the setter method:
From your code,
self.choices
implicitly calls setChoices method. So newly allocated NSMutableDictionary's retain count become 2 not 1, result in object leak.您应该释放属性
choice
引用的成员变量 (ivar)。因此,假设有一个成员变量_choice
然后像这样释放它:应该可以。
或者,如果您像这样重写它,可能会更清楚为什么存在泄漏:
You should be releasing the member variable (ivar) that the property
choice
refers to. So assuming there is a member variable_choice
then releasing it like this:should work.
Alternatively, if you rewrote it like this it might make it clearer why there is a leak: