views:

425

answers:

1

I´m new in iPhone development and I have this memory leak.

I´m using an NSMutableArray to retreive the content of a .plist file located in the Documents directory.

The first time I use it, everything goes fine, but if I call it several times I get a memory leak.

This is my code:

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  NSArray *paths = NSSearchPathForDirectoriesInDomains
                       (NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
     //make a file name to write the data to using the
     //documents directory:
  fullFileName = [NSString stringWithFormat:@"%@/SavedArray", documentsDirectory];
     //retrieve your array by using initWithContentsOfFile while passing
     //the name of the file where you saved the array contents.
  savedArray = nil;
  savedArray = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
  self.composedArray = [savedArray copy];
  [savedArray release];
  [self.tableView reloadData];
}

I release it every time the view disappears

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [composedArray release];
  composedArray = nil;
  [savedArray release];
}

I'm using Instruments and this shows me that the memory leak source is this line of code:

savedArray = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];

I don´t know how solve this leak, if anyone can share any solution to this I would really appreciate it.

Thanks in advance.

+3  A: 

How is the declaration of the property composedArray?

If the declaration is:

@property(retain) id composedArray;

that's where the memory leak is. copy increments the reference count, and so does retain. If anytime you assign to composedArray you'll be assigning a copy (as it seems by reading your code) you should declare your property as:

@property(copy) id composedArray;

and then change your code to do:

self.composedArray = savedArray;

(the copy will happen in the synthethised accessor).

pgb
I change my code to yours, but nothing seems to change, i think the real problem is that i reuse the NSMutableArray every time the view appear and this not release at all.
Jonathan
I move these lines of code to my viewdidLoad and everything works perfect, thats because im not reusing the NSMutableArray, but i need to reuse it, how can i do this?
Jonathan
Jonathan: If you want to hold on to the mutable array, assign it directly to the instance variable—don't make a copy of it and assign that. The code in your question makes a copy (that is what `copy` does), stores the copy in the instance variable, and drops the original on the floor—hence the leak. You should re-read the memory management rules: http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html
Peter Hosey