开发者

Objective-c addObject in loop causes memory leak

I have found a similar issue: NSMutableArray addObject in for loop - memory leak

But none of those suggestions seem to fix my problem.

I have a simple loop where I'm creating an object and adding it to an array. When I try to release the object at the end of each loop the app crashes with "EXC_BAD_ACCESS". If I don't release the object I get leaked memory:

In .h

NSMutableArray *mainlist;
...
@property (nonatomic, retain) NSMutableArray *mainList;

In .m

@synthesize mainlist;
...

for (int i = 0; i < [self.objects count]; i++) {

    MyObj *myObj = [[MyObj alloc] init];

    myObj.title = [[开发者_开发百科self.objects objectAtIndex: i] valueForKey: @"title"];

    [self.mainlist addObject:myObj];

    [myObj release]; // crashes with release
}

MyObj just has some properties:

@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *date_text;
...
@synthesize title;
@synthesize date_text;

- (void)dealloc
{
    [super dealloc];

    [title release];
    [date_text release];
}

@end

Any help would be much appreciated.

Thanks.


Crashes cause you first call dealloc of superclass and then try to release attributes. Change this to:

- (void)dealloc
{
    [title release];
    [date_text release];

    [super dealloc];
}

And also: I'm almost certain that your self.mainlist is nil, when you're adding objects there. Creating a property doesn't mean that the attribute would be initialized automatically.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜