iosmemory-leaksnsmutablearrayplistinitwithcontentsoffile

initWithContentsOfFile Plist in viewWillAppear memory leak


I am loading in my plist files as below in ViewVillAppear. On first load I don't have a leak however pressing other tabBar buttons/items and returning to this view I get a leak. I have released this NSMutableArray in the dealloc however it still leaks. Little confused as to why. (The theProducts3 is an NSMutableArray just as an ivar in .h and its not @property or retained)

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];  

NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"basket.plist"];
theProducts3 = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];

NSLog(@"Number of objects in item array %i", [theProducts3 count]);
}

Releasing the NSMutable array here.

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

Any pointers most appreciated! Thanks...


Solution

  • dealloc is not the inverse of viewWillAppear:. It's the inverse of alloc. The inverse of viewWillAppear: is viewWillDisappear:.

    What is happening is that when your view is appearing, you are allocating memory, then you are going to a different view controller, coming back, your view is appearing again, and you are allocating yet more memory, thus leaking the original memory.

    If your array only needs to hang around so long as your views are in memory, then allocate it in viewDidLoad: and release it in viewDidUnload: and dealloc. Remember to set the instance variable to nil after releasing it.