Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
Kyle Avatar asked May 06 '10 16:05

Kyle


People also ask

How do I add elements to NSArray?

If you create an NSArray you won't be able to add elements to it, since it's immutable. You should try using NSMutableArray instead. Also, you inverted the order of alloc and init . alloc creates an instance and init initializes it.

What is the key difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is a literal in Objective-C?

In Objective-C, any character, numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object initialized with that value. C's type suffixes may be used to control the size of numeric literals.

How do you create an integer array in Objective-C?

You can use a plain old C array: NSInteger myIntegers[40]; for (NSInteger i = 0; i < 40; i++) myIntegers[i] = i; // to get one of them NSLog (@"The 4th integer is: %d", myIntegers[3]);


1 Answers

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.

like image 128
malhal Avatar answered Oct 19 '22 14:10

malhal