【问题标题】:Help with Memory leak: init NSMutableArray from file帮助解决内存泄漏:从文件中初始化 NSMutableArray
【发布时间】:2011-09-02 05:36:11
【问题描述】:

在我的应用程序中,我需要从文件中加载列表,所以我实现了这个方法来加载列表:

-(void)loadList
{
    NSString *filePath = [self dataFilePath];  //This is a method return the path of file
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
        self.list = [[NSMutableArray alloc]initWithArray:tempArray];
        [tempArray release];
    }
}

self.list 是一个(保留)属性。

当我初始化 selfl.list 时,我认为泄漏来自 [alloc]。我用过

self.list = [[[NSMutableArray alloc]initWithArray:tempArray]autorelease];

但应用程序由于 EXC_BAD_ACCESS 而崩溃。所以我很困惑如何解决这个问题。

感谢您的任何建议。

【问题讨论】:

  • 试试这个代码self.list = [NSMutableArray arrayWithArray:tempArray];

标签: iphone memory-leaks nsmutablearray


【解决方案1】:

只需分配,

self.list = tempArray;

由于 tempArray 已经是一个数组,您不必从它创建另一个数组。您可以直接分配给 self.list

【讨论】:

    【解决方案2】:
      There is no need to allocate another time for array .So just assign directly
    
        -(void)loadList
       {
    NSString *filePath = [self dataFilePath];  //This is a method return the path of file
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
        self.list = [tempArray copy];
        [tempArray release];
    }
     }
    

    【讨论】:

    • 您正在构建和分析?
    【解决方案3】:

    不要自动释放它。 (我猜)。

    【讨论】:

      【解决方案4】:

      您的列表属性是分配还是保留? 如果它是保留,那么你应该改变这个:

      self.list = [[NSMutableArray alloc]initWithArray:tempArray];
      

      到这里:

      self.list = [[NSMutableArray arrayWithArray:tempArray];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-28
        • 2016-10-14
        • 1970-01-01
        • 2011-02-18
        • 1970-01-01
        • 2012-07-29
        相关资源
        最近更新 更多