70

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
}
C.Johns
  • 10,185
  • 20
  • 102
  • 156

2 Answers2

147
if ([mystring isEqualToString:@"Johns"]){
    //do some stuff in here
}
David Manpearl
  • 12,362
  • 8
  • 55
  • 72
Vanya
  • 4,973
  • 5
  • 32
  • 57
4

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.

Robert
  • 37,670
  • 37
  • 171
  • 213
  • When would you want to use the `location` approach as opposed to a for loop with the `isEqualToString` method? – Pavan Jan 20 '14 at 18:09
  • 1
    @Pavan Its a little easier to use `indexOfObject` than a for loop (fewer lines of code). Other than that there is little difference. The NSSet method can be faster than looping though an array for large sets, but for most cases it will not be significant. – Robert Jan 20 '14 at 19:33