views:

38

answers:

2

Thanks again for the help.

I have a simple action that checks the stringValue of a textField, and if it matches - a status message prints in a second textField:

 if 

 (textField.stringValue == (@"Whatever" )){
 [outputDisplay setStringValue:@"Success"];

My question is how do I implement multiple input stringValue options in this method? For example "Whatever" "Whatever1, Whatever2" all return "Success" in the outputDisplay.

thanks.

Paul

+5  A: 

Firstly, to check for equality of NSString-s you should use -isEqualToString:. == compares the pointer values which often returns NO even if the two strings' contents are the same.

To check if the text field match multiple strings, you connect them with the || (or) operator, so you get

NSString* st = textField.stringValue;
if ([st isEqualToString:@"Whatever"] || [st isEqualToString:@"Whatever1"] || [st isEqualToString:@"Whatever2"]) {
  [outputDisplay setStringValue:@"Success"];
KennyTM
Thank you very much, Kenny. Very helpful.Paul
paul
+5  A: 

Create a set of answers you're looking for and test if the string in question is in there.

NSSet *successStrings = [NSSet setWithObjects:@"Whatever1",
                                              @"Whatever2",
                                              @"Whatever3",
                                              nil];
if ([successStrings containsObject:st]) {
    [outputDisplay setStringValue:@"Success"];
}

(An array would also work, but a set is specialized for testing membership, so it's a better fit for what we're doing here.)

Chuck
This is good when the set is large and you remember to cache the set. Otherwise the cost to construct the set will overwhelm the cost to test membership.
KennyTM
This is optimized for readability and ease of updating rather than performance. Neither way should be particularly taxing even on an iPhone. I always prefer less code unless I've profiled and determined that it's creating a performance problem.
Chuck
Thank You as well. Very helpful.Paul
paul