views:

49

answers:

1

Hi, 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"];
}
+2  A: 

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.

filipe
Thanks for the quick reply. I implemented the changes described above. And made sure that the variable ("fields") that the returned array is assigned to has a retain. However somewhere in my code this variable is wiped and when I attempt to use it, it crashes. I think it may have something to do with not retaining this "[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath]" and then attempting to use it with this statement: "[[fields objectAtIndex:index] objectForKey:@"costAtHour"];"
wibo
Further investigated, showed me that I wasn't using self.fields when accessing that property and this is what was causing the crash.Thanks
wibo
it might help to see the .plist entry for `fields` dictionary implied by the call.
falconcreek