Do I need to assign a string to a variable before matching it with another?

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

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

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

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

+85
variables objective-c cocoa-touch
Aug 19 '09 at 22:34
source share
4 answers

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

No, why not just do:

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

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

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

Yes, you can do something like:

 UILabel *label = ...; if([someString isEqualToString:label.text]) { // Do stuff here } 
+178
Aug 19 '09 at 22:36
source share
 if ([statusString isEqualToString:@"Wrong"]) { // do something } 
+26
Aug 19 '09 at 22:36
source share

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

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

Although the above works, it contains a saved NSString variable, which you will then need to explicitly release after you finish it.

The next time you want to use a string variable, you can use the @ symbol in a much more convenient way:

 NSString *myString = @"SomeText"; 

It will be auto-implemented when you are done with it to avoid memory leak ...

Hope this helps!

+8
Aug 19 '09 at 22:59
source share

You can also use the methods of the NSString class, which will also create an autodetect instance and have more options, such as formatting strings:

 NSString *myString = [NSString stringWithString:@"abc"]; NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42]; 
+2
Aug 20 '09 at 8:30
source share



All Articles