【问题标题】:Why is this Objective-C code leaking memory?为什么这个 Objective-C 代码会泄漏内存?
【发布时间】:2010-11-30 03:23:16
【问题描述】:

为什么会泄漏?

arrayOfPerformances 是一个合成的NSMutableArray(nonatomic, retain) 属性。

currentPerformanceObject 是合成的 Performance *(nonatomic, retain) 属性。

Performance 是一个自定义类

if(self.arrayOfPerformances == nil)
    {
        self.arrayOfPerformances = [[NSMutableArray alloc]init];
    }

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;

【问题讨论】:

    标签: iphone objective-c memory-leaks


    【解决方案1】:

    您正在创建一个新数组在此行中同时保留它,因为您正在调用带有点符号的(retain) 属性设置器:

    // Your property
    @property (nonatomic, retain) NSMutableArray *arrayOfPerformances;
    
    // The offending code
    self.arrayOfPerformances = [[NSMutableArray alloc]init];
    

    因此,本地创建的数组正在泄漏,因为您没有释放它。您应该自动释放该数组,或创建一个临时本地变量,分配,然后释放本地变量,如下所示:

    // Either this
    self.arrayOfPerformances = [[[NSMutableArray alloc] init] autorelease];
    
    // Or this (props Nick Forge, does the same as above)
    self.arrayOfPerformances = [NSMutableArray array];
    
    // Or this
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    self.arrayOfPerformances = newArray;
    [newArray release];
    

    【讨论】:

    • 尼克说了什么;使用[NSMutableArray array]
    • 哇,那个二传手真让我心烦意乱。我花了几个小时梳理我的代码,试图找出泄漏的位置,最后隔离了该代码,但我终其一生都无法弄清楚出了什么问题。谢谢一百万!
    • @Mausimo:很高兴我终于找到了它:)
    【解决方案2】:

    如果您的.arrayOfPerformances 属性从未被释放(通常会在-dealloc 中释放),那么数组本身以及数组中的任何对象都会在该对象被释放时泄漏。

    您需要在-dealloc 中释放这两个属性:

    - (void)dealloc
    {
        ... other deallocs
        self.arrayOfPerformances = nil;
        self.currentPerformanceObject = nil;
        [super dealloc];
    }
    

    另外,正如@BoltClock 所指出的,您需要释放或自动释放您的NSMutableArray。最好的方法是使用 autoreleased 方法对其进行初始化:

    self.arrayOfPerformances = [NSMutableArray array];
    

    另外,您不需要释放您的currentPerformanceObject,您只需将该属性设置为nil,因为将retained 属性设置为nil 将为您释放它。您的代码应该看起来像这样:

    if (self.arrayOfPerformances == nil) {
        self.arrayOfPerformances = [NSMutableArray array];
    }
    [self.arrayOfPerformances addObject:self.currentPerformanceObject];
    self.currentPerformanceObject = nil;
    

    【讨论】:

    • 我一直忘记array 方法:)
    【解决方案3】:

    这行是罪魁祸首:

    self.arrayOfPerformances = [[NSMutableArray alloc]init];
    

    在 alloc/init 之后保留计数为 1。通过arrayOfPerformances 属性设置器设置值会再次增加保留计数(因为它是保留属性)。

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2011-10-21
      • 2012-06-01
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多