Kyle
Kyle

Reputation: 1672

How do I create an NSArray with string literals?

I'm attempting to create an NSArray with a grouping of string literals, however I get the compile error "Initializer element is not constant".

NSArray *currencies = [NSArray arrayWithObjects:@"Dollar", @"Euro", @"Pound", nil];

Could someone point out what I'm doing wrong, and possibly explain the error message?

Upvotes: 32

Views: 56184

Answers (6)

malhal
malhal

Reputation: 30627

New syntax for creating an array with string literals:

NSArray *currencies = @[@"Dollar", @"Euro", @"Pound"];

To fix your complication error the code must be in a method. If you want to use it statically then create a class method that follows the singleton pattern.

Upvotes: 76

microspino
microspino

Reputation: 7781

Although this is old, please notice that Apple committed a new patch to the llvm project adding support for new Objective-C literal syntax for NSArray, NSDictionary and NSNumber.

See here and here

Upvotes: 3

jlehr
jlehr

Reputation: 15597

It sounds like Chuck has spotted the problem. One thing you want to be aware of though in coding your solution is that you'll want to avoid storing an autoreleased instance of NSArray in a static variable. Also, a common pattern for these situations is to write a class method that creates and returns the value stored in the static variable, like so:

+ (NSArray *)currencies
{
    static NSArray *_currencies;

    // This will only be true the first time the method is called...
    //
    if (_currencies == nil)
    {
        _currencies = [[NSArray alloc] initWithObjects:@"Dollar", @"Euro", @"Pound", nil];
    }

    return _currencies;
}

Upvotes: 7

Chuck
Chuck

Reputation: 237060

This isn't a problem with the NSArray creation itself (you would get the same error if you wrote [NSArray array] instead), but with where you've written it. I'm guessing this is a global or file-static NSArray. In C, that kind of variable has to have a constant initializer — meaning not a function call (or, by extension, a method call). The solution is to put the actual creation and assignment of the array into a method that will be called before you need the array, such as initialize.

Upvotes: 18

Adirael
Adirael

Reputation: 9448

I'm a newbie in objective-c, but I think that the correct code is:

NSArray *currencies = [[NSArray alloc] initWithObjects:@"Dollar", @"Euro", @"Pound", nil];

I am not sure tho.

Upvotes: 2

Dave DeLong
Dave DeLong

Reputation: 243156

There's nothing wrong with that code. Are you sure the error is being produced at that line?

Upvotes: 0

Related Questions