Reputation: 967
am having some trouble with attempting to remove a memory leak from my code. In the code below, I get a memory leak on the line "configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];" however when I remove the retain, the application crashes and changing the retain to an autorelease also causes a crash.
thanks, William
-(NSArray*)decodeConfigurationFile:(NSString*)fileName{
NSArray* configurationArray = [[NSArray alloc] init];
NSString *controllerConfigurationFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
if (controllerConfigurationFilePath != nil) {
// returns array of items storing the data for form
configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];
}
// returns fields dictionary objects from plist into an array
return [[configurationArray objectAtIndex:0] objectForKey:@"fields"];
}
Upvotes: 0
Views: 591
Reputation: 3380
The problem seems to be that you're allocating an array by doing
NSArray* configurationArray = [[NSArray alloc] init];
and then you're creating a new array by doing
configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];
without ever releasing the first array you created. The first line should be just
NSArray* configurationArray = nil;
And you shouldn't need the retain, since it's a local variable and you are not keeping a pointer to that array beyond the scope of that function.
The crash probably comes from the fact that the object calling this method is probably not retaining the object returned by this method, which will be deallocated along with the array if nothing else is retaining it. So when you're trying to access that object somewhere else in your code, the object is no longer there. If the calling object needs to keep this returned object, the calling object should retain the returned object.
Upvotes: 2