【问题标题】:How to solve the leaks when allocating the NSMutableArray in Objective-C在 Objective-C 中分配 NSMutableArray 时如何解决泄漏问题
【发布时间】:2010-05-24 10:53:19
【问题描述】:

iPhone 的主视图控制器出现泄漏。

当我调用这个方法时,我将它们插入到filteredListCount 数组中,因为当我搜索时我需要显示来自filteredListCount 数组的列表,否则customerArray

此功能运行良好,但在分配时我在以下方法中出现泄漏:filteredListCount = [[NSMutableArray alloc] initWithCapacity: [customerArray count]];

这是我的应用程序的第一个视图控制器,我正在显示列表,我也允许从列表中搜索。

- (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";
}

【问题讨论】:

    标签: iphone objective-c memory-leaks nsmutablearray


    【解决方案1】:

    为防止在分配数组时发生内存泄漏,您可以检查它是否已经存在。另外自动释放它。分配 TableViewCell 模式也是一样的:

    if(filteredListCount == nil){
        filteredListCount = [[[NSMutableArray alloc] initWithCapacity:[customerArray count]] autorelease];
    }
    

    【讨论】:

    • 请注意,在使用 ARC 时这不是有效的方法
    【解决方案2】:

    此功能运行良好,但 我在以下方法中出现泄漏 分配时:filteredListCount = [[NSMutableArray 分配] initWithCapacity: [customerArray 计数]];

    iPhone 上没有垃圾收集。如果filteredListCount 已经指向一个已分配的内存块,并且您为其分配了其他内容,则该块将继续存在。

    先清空filteredListCount。

    if(filteredListCount){
      [filteredListCount release];
      filteredListCount = nil;
    }
    // now you're sure filteredListCount is empty
    filteredListCount = [[NSMutableArray alloc] initWithCapacity: [customerArray count]];
    

    或者,只使用一个保留属性。

    【讨论】:

    • 如果filteredList是一个属性,请务必使用self.filteredList表示法,否则它不会调用合成的访问器方法,也不会保留数组。
    【解决方案3】:

    customerArray 和filteredListCount 何时、何地以及如何声明?

    如果 filtersListCount 是一个属性,使用 self.filteredListCount=.... 来正确释放之前的内存。您可能还想做 [filteredListCount removeAllObjects]

    也不清楚您的代码中是否有任何 dealloc(这显然是一个泄漏)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2011-07-29
      • 2011-05-28
      • 2012-08-19
      相关资源
      最近更新 更多