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
}
}
}
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 returnThese objects are different
because although the strings are the same, they are stored at different locations in memory: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 ofNSString
. This code will returnThese strings are the same
because it compares the value of the string objects rather than their pointer values:To compare arbitrary Objective-C objects you should use the more general
isEqual:
method ofNSObject
.-isEqualToString:
is an optimized version of-isEqual:
that you should use when you know both objects areNSString
objects.