2

I am looking for the best way to pass a Difficulty level between View Controllers.

At present I have this setup as a String. There are three options Easy/Medium/Hard, I know this is not the best way to do this so am looking for what would be the correct approach here.

At the moment I check the tag on the button and set a string value like below:

if (sender.tag == 10) {
    self.turnDifficulty = @"Easy";
} else if (sender.tag == 20) {
    self.turnDifficulty = @"Medium";
} else if (sender.tag == 30) {
    self.turnDifficulty = @"Hard";
}

I then pass the value over in the prepareForSegue method. What is the alternate to this approach? Although there is no issue here and this works fine, it is not very clean working with strings here.

StuartM
  • 6,743
  • 18
  • 84
  • 160

2 Answers2

4

One alternative to working with strings in Objective-C (indeed, in C and C++ as well) us using an enumeration:

typedef enum Difficulty {
    DIFFICULTY_EASY
,   DIFFICULTY_MEDIUM
,   DIFFICULTY_HARD
} Difficulty;

Declare this enum in a header included from all your view controllers, and use enumeration constants as if they were numeric constants. The language will ensure that the constants remain distinct, even when you choose to add more items to the enumeration.

When you declare a @property or a parameter of type Difficulty, do not use an asterisk, because enums are primitive types, not reference types. For example:

@property (nonatomic, readwrite) Difficulty difficultyLevel;

or

-(void)openWithDifficulty:(Difficulty)level;

EDIT : (thanks, Rob!)

As of Xcode 4.4, you might also use an explicit fixed underlying type, e.g.

typedef enum Difficulty : NSUInteger {
    kDifficultyEasy
,   kDifficultyMedium
,   kDifficultyHard
} Difficulty;
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

If your problem is just working with string you should declare an enumeration.

Write in a Enum.h that will be imported by all your controllers :

typedef enum
{
    EASY = 0,
    MEDIUM,
    HARD
}   DIFFICULTY;

Just for someone-who-wouldn't-know-what-this-is' information, this declare a restrictive integer type that can have only 3 values : EASY (= 0), MEDIUM (= 1), HARD (= 2).

It will be far cleaner (and better for your memory management).

shinyuX
  • 1,519
  • 1
  • 9
  • 20