Checking for equality in Objective-C

suse picture suse · Feb 19, 2010 · Viewed 19.4k times · Source

How do i check the key in dictionary is same as the string in method parameter? i.e in below code , dictobj is NSMutableDictionary's object , and for each key in dictobj i need to compare with string. How to achieve this ? Should i typecase key to NSString??

-(void)CheckKeyWithString:(NSString *)string
{
   //foreach key in NSMutableDictionary
   for(id key in dictobj)
     {
       //Check if key is equal to string
       if(key == string)// this is wrong since key is of type id and string is of NSString,Control doesn't come into this line
          {
           //do some operation
          }
     }
}

Answer

Rob Keniger picture Rob Keniger · Feb 19, 2010

When you use the == operator, you are comparing pointer values. This will only work when the objects you are comparing are exactly the same object, at the same memory address. For example, this code will return These objects are different because although the strings are the same, they are stored at different locations in memory:

NSString* foo = @"Foo";
NSString* bar = [NSString stringWithFormat:@"%@",foo];
if(foo == bar)
    NSLog(@"These objects are the same");
else
    NSLog(@"These objects are different");

When you compare strings, you usually want to compare the textual content of the strings rather than their pointers, so you should the -isEqualToString: method of NSString. This code will return These strings are the same because it compares the value of the string objects rather than their pointer values:

NSString* foo = @"Foo";
NSString* bar = [NSString stringWithFormat:@"%@",foo];
if([foo isEqualToString:bar])
    NSLog(@"These strings are the same");
else
    NSLog(@"These string are different");

To compare arbitrary Objective-C objects you should use the more general isEqual: method of NSObject. -isEqualToString: is an optimized version of -isEqual: that you should use when you know both objects are NSString objects.

- (void)CheckKeyWithString:(NSString *)string
{
   //foreach key in NSMutableDictionary
   for(id key in dictobj)
     {
       //Check if key is equal to string
       if([key isEqual:string])
          {
           //do some operation
          }
     }
}