3

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

3
  • 3
    Have you initialized terms array? Commented Sep 8, 2011 at 1:55
  • Are you positive that [lines objectAtIndex:i] is returning what you think it is? Commented Sep 8, 2011 at 1:55
  • possible duplicate of NSMutableArray addObject not working Commented Sep 8, 2011 at 6:37

2 Answers 2

7

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];
Sign up to request clarification or add additional context in comments.

4 Comments

Figured I was forgetting something. Works now
It is an odd "feature" of Objective C that a call on a nil pointer is happily ignored, so even though your mutable array was never created, no errors are raised. C or Java would have given you some sort of null pointer exception, fairly rapidly reminding you that you forgot to create the darned thing.
@Daniel It is something you have to keep in mind when you use Objective C. The feature part is that you don't have to speckle your code with checks to see if your pointer is nil. Much cleaner code.
Yeah, it's got its advantages. But, as is often the case with such features, there's a bit of a deal with the devil involved.
0

"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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.