Is it necessary to assign a string to a variable before comparing it to another?

Bryan picture Bryan · Aug 20, 2009 · Viewed 107.7k times · Source

I want to compare the value of an NSString to the string "Wrong". Here is my code:

NSString *wrongTxt = [[NSString alloc] initWithFormat:@"Wrong"];
if( [statusString isEqualToString:wrongTxt] ){
     doSomething;
}

Do I really have to create an NSString for "Wrong"?

Also, can I compare the value of a UILabel's text to a string without assigning the label value to a string?

Answer

Alex Rozanski picture Alex Rozanski · Aug 20, 2009

Do I really have to create an NSString for "Wrong"?

No, why not just do:

if([statusString isEqualToString:@"Wrong"]){
    //doSomething;
}

Using @"" simply creates a string literal, which is a valid NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

Yes, you can do something like:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 
}