Chris
Chris

Reputation: 7310

Objective C: NSMutableArray does not retain objects

I'm so stumped by this, I set the object in the array, but when I check it after they're all set, it comes up as (null)

for (int i = 0; i < [lines count]; i+=2) {
    [terms addObject:[lines objectAtIndex:i]];
    NSLog(@"%@",[terms objectAtIndex:i]);
}

Am I doing something wrong? terms is declared in the header, set as a property, and synthesized as an NSMutableArray

Upvotes: 3

Views: 1563

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61341

"Synthesized as a NSMutableArray" - that's weird wording. In ObjC, @synthesize does not initialize variables - just generates a getter and a setter method. You still have to allocate the variable somehow - either by assigning to a property, or by setting the corresponding ivar directly. init is a nice place to do that.

Upvotes: 0

Steve Moser
Steve Moser

Reputation: 7797

You have to first alloc and init the array before you use it. Setting the property makes it accessible outside the class and the synthesizer sets up the getter and setter but it doesn't alloc and init it.

NSMutableArray* terms = [[NSMutableArray alloc] init];

Upvotes: 7

Related Questions