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?
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.
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.
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.
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With