iPhone NSMutableArray内存泄漏

时间:2010-02-26 15:36:56

标签: iphone memory-leaks nsmutablearray

Xcode Instruments声称以下代码会导致内存泄漏。据我所知,在分配财产时会发生以下情况:
*旧值是自动释放的 *保留新值
*显然分配了新值 考虑到这一点,我怎么会有内存泄漏,我该如何解决?

“TestProjectViewController.h”:

#import <UIKit/UIKit.h>

@interface TestProjectViewController : UIViewController {
    NSMutableArray* array;
}

@property (nonatomic, retain) NSMutableArray* array;

@end

“TestProjectViewController.m”:

#import "TestProjectViewController.h"

@implementation TestProjectViewController

@synthesize array;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    for(int i = 0; i < 5; i++) {
        self.array = [[NSMutableArray alloc] init];
        [self.array addObject:@"Hello world #1"];
        [self.array addObject:@"Hello world #2"];
    }
}

4 个答案:

答案 0 :(得分:5)

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

这里保留两个新的数组对象 - 分配它然后在setter方法中。以下之一应该解决这个问题:

self.array = [[[NSMutableArray alloc] init] autorelease];
// or
self.array = [NSMutableArray arrayWithCapacity:someNumber];

并且也不要忘记以dealloc方法释放你的数组。

答案 1 :(得分:1)

每次循环,你alloc一个新数组。每个数组都以refcount为1开始,并且赋值给属性会将其增加到2.您需要release这些数组,以便属性是对象的唯一“所有者”。

例如,你可以这样做:

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    for(int i = 0; i < 5; i++) {
        self.array = [[NSMutableArray alloc] init];
        [self.array addObject:@"Hello world #1"];
        [self.array addObject:@"Hello world #2"];
        [self.array release];
    }
}

或者这样做:

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    for(int i = 0; i < 5; i++) {
        self.array = [[[NSMutableArray alloc] init] autorelease];
        [self.array addObject:@"Hello world #1"];
        [self.array addObject:@"Hello world #2"];
    }
}

答案 2 :(得分:1)

您正在循环中初始化数组。至少你没有必要将数组的值赋给另一个对象。在这种情况下,您还必须在循环内释放它。你不是要释放内存。由于您为数组分配了内存,因此您也应该释放它:

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
  self.array = [[NSMutableArray alloc] init];//You just need to initialize the array just once
  for(int i = 0; i < 5; i++) {
    [self.array addObject:@"Hello world #1"];
    [self.array addObject:@"Hello world #2"];
  }
}
//Finally its necessary to release the memory when the app quits using the release method 
[self.array release]

答案 3 :(得分:0)

此方法泄漏,因为alloc/init具有隐式保留,然后该属性再次保留它。这导致每个阵列被保留两次。您可以autorelease数组,也可以在循环结束时release

作为旁注,为什么要在循环中分配这样的属性?只有最后一个数组将保留在该属性中。相反,您可以使用局部变量并仅分配最后一个数组:

- (void)applicationDidFinishLaunching:(UIApplication *)application { 
    NSMutableArray *tempArray = nil;

    for(int i = 0; i < 5; i++) {
        tempArray  = [[[NSMutableArray alloc] init] autorelease];
        [tempArray addObject:@"Hello world #1"];
        [tempArray addObject:@"Hello world #2"];
    }

    self.array = tempArray;
}