NSCFArray在NSMutablearray分配中泄漏

时间:2010-03-23 06:47:12

标签: objective-c memory-leaks

我在这次分配中得到了泄密

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)searchBar:(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];
}

2 个答案:

答案 0 :(得分:3)

每次调用filteredListContent时,您的代码都会分配reloadTable的新实例,这通常会在应用程序的生命周期内发生几次。这会导致泄漏,因为旧实例未被释放。

解决此问题的最佳(也是最简单)方法是将filteredListContent设为retain属性:

  你班级标题中的

@property (nonatomic, retain) NSMutableArray * filteredListContent;
  reloadTable方法中的

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

请注意在第二个代码段中使用self.。该语法通知Cocoa它应该使用属性访问器来设置filteredListContent的值,然后它将为您发送相应的retainrelease消息。

答案 1 :(得分:0)

您发布了三个与内存泄漏有关的几乎完全相同的问题。阅读Apple's Memory Management Programming Guide可能对您有所帮助。