How to solve the leaks when allocating the NSMutableArray in Objective-C
I am getting leaks in Master view controller of iPhone.
When I call this method, I am inserting them into filteredListCount
array, because when I search I need to show the list from filteredListCount
array otherwise customerArray
.
This functionality is working fine but I am getting leaks 开发者_运维知识库in the method below at allocation: filteredListCount = [[NSMutableArray alloc] initWithCapacity: [customerArray count]];
This is the first view controller of my application, I am showing the list and I am also allowing to search from a list.
- (void)parser:(CustomerListLibXmlParser *)parser addCustomerObject:(Customer *)customerObj1
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[customerArray addObject:customerObj1];
filteredListCount = [[NSMutableArray alloc] initWithCapacity: [customerArray count]];
[filteredListCount addObjectsFromArray: customerArray];
[theTableView reloadData];
}
- (void)parser:(CustomerListLibXmlParser *)parser encounteredError:(NSError *)error
{
}
- (void)parserFinished:(CustomerListLibXmlParser *)parser
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.title=@"Customers";
}
To prevent memory leak when allocate the array you could check if it exists already. Additionally autorelease it. That is the same to allocate TableViewCell pattern:
if(filteredListCount == nil){
filteredListCount = [[[NSMutableArray alloc] initWithCapacity:[customerArray count]] autorelease];
}
This functionality is working fine but I am getting leaks in the method below at allocation: filteredListCount = [[NSMutableArray alloc] initWithCapacity: [customerArray count]];
There's no garbage collection on the iphone. If filteredListCount is already pointing to a block of memory that's been allocated, and you assign something else to it, that block will continue to exist.
Empty out filteredListCount first.
if(filteredListCount){
[filteredListCount release];
filteredListCount = nil;
}
// now you're sure filteredListCount is empty
filteredListCount = [[NSMutableArray alloc] initWithCapacity: [customerArray count]];
Or, just use a retain property instead.
when, where and how are customerArray and filteredListCount declared ?
IF filteredListCount is a property, use self.filteredListCount=.... to properly release any previous memory. You may also want to do [filteredListCount removeAllObjects]
Its also not clear that you have any dealloc's in your code (which is obviously a leak).
精彩评论