how to check if NSString = a specific string value?

IphoneIosNsstring

Iphone Problem Overview


Hi I am woundering if you can check to see if a NSString equals a specific value say for instance a name of a person?

I am thinking along the lines of

if (mystring == @"Johns"){
    //do some stuff in here
}

Iphone Solutions


Solution 1 - Iphone

if ([mystring isEqualToString:@"Johns"]){
    //do some stuff in here
}

Solution 2 - Iphone

Here is another method you might want to use in some circumstances:

NSArray * validNames = @[ @"foo" , @"bar" , @"bob" ];

if ([validNames indexOfObject:myString].location != NSNotFound) 
{
    // The myString is one of the names in the valid names array
}

Or if you have a large amount of names in the array you could use a NSSet, since finding an object is faster than in an array ((O(Log N) vs O(N))

NSSet * validNamesSet = [NSSet setWithArray:validNames];

if ([validNamesSet containsObject:myString]) 
{
    // This is faster than indexOfObject for large sets
}

These methods work because NSSet and NSArray use isEqual: which will call isEqualToString: for NSString instances.

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
QuestionC.JohnsView Question on Stackoverflow
Solution 1 - IphoneVanyaView Answer on Stackoverflow
Solution 2 - IphoneRobertView Answer on Stackoverflow