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
}
}
}