开发者

Memory leak with an array - objective c

开发者 https://www.devze.com 2023-01-14 03:24 出处:网络
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:controllerConfi

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 *controllerCon开发者_运维问答figurationFilePath = [[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"];
}


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.

0

精彩评论

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