Jonathan
Jonathan

Reputation: 83

NSMutableArray initWithContentsOfFile memory leak

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.

Upvotes: 2

Views: 2503

Answers (1)

pgb
pgb

Reputation: 25001

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).

Upvotes: 5

Related Questions