views:

1302

answers:

1

Hi,

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.

+1  A: 

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;
}
Philippe Leybaert
Thanks. I don't know why I didn't think that that would work. It's pretty logical. Must be this land of square brackets that is causing me to strange in the head!
JonB
There is no real need or purpose in using [NSString string] - just use @"". The "string" factory method is there for consistency, and there for use in the mutable version where it is useful ([NSMutableString string]).
Peter N Lewis
As a general good practice, I'd recommend also saying NSString *aString = nil; It's always good to do that.
jbrennan