nayem
nayem

Reputation: 7585

How to initialize an NSArray of NSString?

I'm using a property of NSArray type. Then I'm trying to initialize or setting values for the NSArray. When I use shorthand assignment, I'm getting the output. But when I'm trying with long initialization style, I'm not getting the result. What should be the right way for the latter??

Here is the code snippet:

@property NSArray * moods;

//shorthand assignment
self.moods=@[@"Happy",@"Sad"];
NSLog(@"Hello %@",[self moods]);

This is working. But when I tried:

//long initialization style
[[self moods]initWithObjects:@"Happy",@"Sad", nil];
NSLog(@"Hello %@",[self moods]);

This isn't doing the same way. Suggest me something please.

Upvotes: 0

Views: 3224

Answers (3)

André Slotta
André Slotta

Reputation: 14030

just some alternative approach without dots... ;)

[self setMoods:@[@"Happy", @"Sad"];

Upvotes: 1

andre
andre

Reputation: 280

The answer above is completely correct. I would love just to add a comment for the sake of completeness but I can't so I'll add an extra answer to give all the options.

You can use the convenience initializers if you always get confused with the order of the alloc and init. Or if you want to have cleaner code.

self.moods = [NSArray arrayWithObjects:@"Happy",@"Sad", nil];

But the answer above it's perfect and I personally prefer the more explicit alloc init pattern.

Upvotes: 0

Patrick Goley
Patrick Goley

Reputation: 5417

The second example should be:

self.moods = [[NSArray alloc] initWithObjects:@"Happy",@"Sad", nil];

alloc must always be called before init to actually allocate the memory for the object. [self moods] is going to return nil until you assign something to self.moods.

Edit:

If you really want to avoid the assignment by property dot notation syntax for whatever reason, you can use the setter method instead:

[self setMoods: [[NSArray alloc] initWithObjects:@"Happy",@"Sad", nil]];

Upvotes: 3

Related Questions