开发者

Problem with a NSMutableArray Leak

I thought I knew how to deal with memory leaks and arrays, but then this pops up. I can't figure pout why this is leaking:

//  MyViewController.h

NSMutableArray      *myMutableArray;

@property (nonatomic, retain) NSMutableArray *myMutableArray;

//  MyViewController.m

@synthesize myMutableArray;

- (void) viewDidLoad {

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

    . . .

    for (NSUInteger i = 0; i < someCount; ++i) {

        [self.myMutableArray addObject:[NSString stringWithFormat: @"%@",myString]];

    }

}

- (void)viewDidUnload {
   开发者_StackOverflow self.myMutableArray = nil
}

- (void)dealloc {
     [myMutableArray release];
} 


Your problem is here:

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

It should be:

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

Or:

if (myMutableArray == nil) {
   myMutableArray = [[NSMutableArray alloc] init];
}

Explanation:

Since you are using retain as a property mutator attribute, the object will be retained when it is passed to the property setter, therefore you have a leak when you retain an object you already have ownership of.

The solution to this is to either a) Pass an autorelease-d object to the property setter or b) Assign the ivar directly to the alloc-ed object.


You're allocating a new array, then setting it to a retain property. Change that line to

self.myMutableArray = [NSMutableArray array]; 


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

should be

self.myMutableArray = [[[NSMutableArray alloc] init] autorelease];

because myMutableArray is a retained property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜