Objective-C 内存问题
我的应用程序中的内存管理存在问题。我有一个 NSDictionary 实例变量,我将其设置为等于在方法中创建的另一个 NSDictionary 。这一切都工作正常,我的应用程序的行为就像我想要的那样,但我在应用正确的内存管理时遇到了困难。
如果我释放本地字典,它最终会导致崩溃,因为该方法被重复调用,因为保存在实例变量中的数据也会被丢弃。这是代码:
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"Names" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.dictAllValues = dictionary;
[dictionary release];
I'm having an issue with the memory management in my application. I have an NSDictionary instance variable that I'm setting equal to another NSDictionary that gets made in a method. This all works fine and my application behaves like I want it to, but I'm having trouble applying the proper memory management.
If I release the local dictionary it eventually causes a crash as the method is called repeatedly, because the data saved in the instance variable is also trashed. Here's the code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"Names" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.dictAllValues = dictionary;
[dictionary release];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建 dictAllValues
使用您的方法
并在 dealloc 方法中释放
Create dictAllValues using
Your method
and release in dealloc method
如何声明
dictAllValues
?通常情况下,它会是:如果是这样,那么代码中的
release
是正确的,您的问题出在其他地方。发布崩溃的回溯,使用构建和分析并修复任何问题,并尝试打开僵尸检测。How do you declare
dictAllValues
? Typically, it would be:If so, then the
release
in your code is correct and your problem lies elsewhere. Post the backtrace of the crash, use Build and Analyze and fix any issues, and try turning on Zombie detection.来自苹果内存管理指南 。
作为基本规则的推论,如果您需要将接收到的对象作为属性存储在实例变量中,则必须保留或复制它。
因此,在本例中将
[dictionary release ];
在dealloc
方法中(或者您可能用于清理的任何其他方法)应该可以正常工作。我假设您的 dictAllValues 属性使用简单的赋值,如果情况并非如此,请告诉我。
From the apple memory management guide.
As a corollary of the fundamental rule, if you need to store a received object as a property in an instance variable, you must retain or copy it.
So, in this case putting
[dictionary release];
indealloc
method instead (or any other method you might use for clean up) should work fine.I assume your
dictAllValues
property uses simple assignment, let me know if that's not the case.