0

I am beginning to delve into iOS development, and am learning Objective C. My background is Java.
I'm attempting to create a simple console game, and have created the following constants:

#import <Foundation/Foundation.h>

static const NSString *ROCK = @"Rock";
static const NSString *PAPER = @"Paper";
static const NSString *SCISSORS = @"Scissors";
static const NSString *LIZZARD = @"Lizzard";
static const NSString *SPOCK = @"Spock";
static const NSArray *WEAPONS = @[SPOCK, ROCK, SCISSORS, LIZZARD, PAPER];

The trouble is that I get an error on the last line: Initializer element is not a compile-time constant.

I tried to figure out what this means -- the closest thing I could find was this question by Fred Collins, where he notes that "This happens because objects works [sic] at runtime." I'm still not entirely sure what the implication of this is -- how is this different from Java? (I can definitely do this in Java!)

Regardless, I need some way of initializing NSArray *WEAPONS, and I can't make the answers to Fred Collin's question work for me without adding another file. (He is using a class for his constants, where as my program is simple enough to be contained in the same file as the main method.)

Community
  • 1
  • 1
James Dunn
  • 7,548
  • 11
  • 47
  • 81

3 Answers3

1

One proper way to initialize the array is to do this:

static const NSString *ROCK = @"Rock";
static const NSString *PAPER = @"Paper";
static const NSString *SCISSORS = @"Scissors";
static const NSString *LIZZARD = @"Lizzard";
static const NSString *SPOCK = @"Spock";
static const NSArray *WEAPONS = nil;

+ (void)initialize {
    WEAPONS = @[SPOCK, ROCK, SCISSORS, LIZZARD, PAPER];
}

The initialize class method is a special class method that will only be called once before any instance is ever created or before any method (class or instance) is ever called.

rmaddy
  • 298,130
  • 40
  • 468
  • 517
0

NSArrays are not allowed to be used like that and must be done inside a method. Most everything with the exception of the NSString is disallowed.

Try something like

static const NSString *ROCK = @"Rock";
static const NSString *PAPER = @"Paper";
static const NSString *SCISSORS = @"Scissors";
static const NSString *LIZZARD = @"Lizzard";
static const NSString *SPOCK = @"Spock";
static const NSArray *WEAPONS = nil;
- (void)init
{
    WEAPONS = @[SPOCK, ROCK, SCISSORS, LIZZARD, PAPER];
}
anders
  • 3,945
  • 2
  • 21
  • 31
  • Do NOT initialize a static value in an instance method unless you at least verify that it is not yet initialized. Better yet is to initialize the static variable in the `initialize` class method. – rmaddy Jan 06 '14 at 17:34
-1

The proper way is to do it in the init method of the object, or

static const NSArray *WEAPONS = @[@"SPOCK", @"ROCK", @"SCISSORS", @"LIZZARD", @"PAPER"];

but I would not recommend this one.

James Dunn
  • 7,548
  • 11
  • 47
  • 81
ninja_iOS
  • 1,161
  • 1
  • 13
  • 20