views:

28

answers:

1

I have an ivar mutable array which i setup in viewDidLoad as follows:

names = [NSMutableArray arrayWithCapacity:30];
[names addObject:@"Joe"];
[names addObject:@"Dom"];
[names addObject:@"Bob"];

Then in a later method, on tap of a button, i do the following, but the array appears to be overreleasing... with Zombie messaged:

int r = arc4random() % [names count];
NSLog(@"%d", r);

How do i fix this?

Thanks.

+5  A: 

+arrayWithCapacity: will return an auto-released object, i.e. in the "later method" this object is likely already deallocated. You need to retain this object to make it available "later".

names = [[NSMutableArray arrayWithCapacity:30] retain];

(alternatively,

names = [[NSMutableArray alloc] initWithCapacity:30];

)

Don't forget to release it in -dealloc.

-(void)dealloc {
   [names release];
   ...
   [super dealloc];
}
KennyTM
Assuming `names` is an iVar and there is a corresponding setter or an `@property`, `self.names = [NSMutableArray array];` would work, as well.
bbum