开发者

Objective-C Memory Issue

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 lik开发者_开发问答e 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];


Create dictAllValues using

 @property(retain) NSDictionary *dictAllValues;

Your method

-(void) myMethod
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"Names" ofType:@"plist"];

NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.dictAllValues = dictionary;
[dictionary release];
}

and release in dealloc method

-(void) dealloc
{
[dictAllValues release];
[super dealloc];
}


How do you declare dictAllValues? Typically, it would be:

 @property(retain) NSDictionary *dictAllValues;

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.


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]; in dealloc 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜