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

Objective CCocoa TouchVariables

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

> 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 
}

Solution 2 - Objective C

if ([statusString isEqualToString:@"Wrong"]) {
    // do something
}

Solution 3 - Objective C

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

Hope that helps!

Solution 4 - Objective C

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBryanView Question on Stackoverflow
Solution 1 - Objective CAlex RozanskiView Answer on Stackoverflow
Solution 2 - Objective CWevahView Answer on Stackoverflow
Solution 3 - Objective Ch4xxrView Answer on Stackoverflow
Solution 4 - Objective CdanielpuntView Answer on Stackoverflow