R – Objective-C switch defines contents of string

objective cstringswitch statement

I've come from a java background, so i'm still getting to grips with some of the ways of doing things with Obj-C.

Depending on a number provided, I want an NSString variable to have different contents.

In java I would do something like this:

string foo;
switch (numberToSwtich){

    case 1:
       foo = "Something!";
       break;
    case 2:
       foo = "Something Else!";
       break;
}

Obviously there are two types of String in objective-c. NSString and NSSMutableString.

The difference being that you can change one at a later date. However, like java, can I initialize a NSString first then set its contents later or do I need to use an NSMutableString?

Something a bit like this…

NSString *aString = [[NSString alloc] init];

switch ([self getNumberOfSides]) {
    case 1:
        aString = @"A String"; 
        break;
    case 2:
        aString = @"Another String"; 
        break;
}

I'm aware there are other-ways of doing this, such as using an NSDictionary with numeric keys for example, but I would like to use a switch.

Thanks.

Best Answer

Your code is perfectly valid. There's no need to use NSMutableString.

Your code does leak memory, because you're not releasing the empty string you allocated using alloc. It's better to use the "string" class method for empty strings:

NSString *aString;

switch ([self getNumberOfSides]) {
        case 1:
                aString = @"A String"; 
                break;
        case 2:
                aString = @"Another String"; 
                break;
        default:
                aString = [NSString string];
                break;
}