开发者

NSCFArray leak in the NSMutablearray allocation

I am getting the leak at this allocation

filteredListContent = [[NSMutableArray alloc] initWithCapacity:[showList count]];

CODE:

-(void)reloadTable
{
    EventListAppDelegate *appDelegate;
    UIApplication app = [UIApplication sharedApplication];
    appDelegate = (EventListAppDelegate *)[app delegate];

    contactList = [appDelegate getAllContactsList];
    inviteeList = [appDelegate getInviteeListForEvent:event.primaryKey];

    if (isInvited == YES)
    {
        showList = [appDelegate getInviteeListForEvent:event.primaryKey];
    }
    else
    {
        showList = [appDelegate getAllContactsList];
    }

    filteredListContent = [[NSMutableArray alloc] initWithCapacity:
                           [showList count]];

    [filteredListContent addObjectsFromArray: showList];

    [self organizeContactItemsIntoIndexes];
    self.title = [event.name capitalizedString];

    [self getToolbar];        
    [theTableView reloadData];
}

- (void)search开发者_StackOverflow中文版Bar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [filteredListContent removeAllObjects]; 

    ContactDTO *currentElement;
    NSRange range;

    for (currentElement in showList)
    {
        range = [currentElement.lastName rangeOfString:searchText
                                         options:NSCaseInsensitiveSearch];

        if(range.location == 0)
        {
            [filteredListContent addObject:currentElement];
        }
    }

    [self organizeContactItemsIntoIndexes];
    [theTableView reloadData];
}

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


Your code will allocate a new instance of filteredListContent every time reloadTable is called, which will usually happen several times during the lifetime of your application. This causes a leak because the old instances are not released.

The best (and easiest) way to fix it would be to make filteredListContent a retain property:

in your class header:

@property (nonatomic, retain) NSMutableArray * filteredListContent;

in your reloadTable method:

self.filteredListContent = [NSMutableArray arrayWithCapacity:[showList count]];

Note the use of self. in the second code snippet. That syntax informs Cocoa that it should use the property accessor to set the value of filteredListContent, which will then send the appropriate retain and release messages for you.


You've posted three nearly-identical questions pertaining to memory leaks. It might be helpful for you to read through Apple's Memory Management Programming Guide.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜