Search code examples
iosobjective-cnsarray

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.


Solution

  • 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]];