Objective-c addObject in a loop causes a memory leak

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

But none of these suggestions seem to fix my problem.

I have a simple loop where I create an object and add it to an array. When I try to release an object at the end of each loop, the application crashes with "EXC_BAD_ACCESS". If I do not free the object, I get a memory leak:

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 has only 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 greatly appreciated.

Thank.

+3
source share
1 answer

Failure leads to the first call to the dealloc superclass, and then tries to free the attributes. Change this to:

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

    [super dealloc];
}

: , self.mainlist , . , .

+3

All Articles