简体   繁体   中英

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 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];

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];
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM