检查Objective-C中的相等性

sus*_*use 13 objective-c iequalitycomparer

如何检查字典中的键与方法参数中的字符串相同?即在下面的代码中,dictobj是NSMutableDictionary的对象,而对于dictobj中的每个键,我需要与string进行比较.怎么做到这一点?我应该指定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
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ger 39

使用==运算符时,您正在比较指针值.这仅适用于您要比较的对象在同一内存地址上完全相同的对象.例如,此代码将返回,These objects are different因为尽管字符串相同,但它们存储在内存中的不同位置:

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

当你比较字符串时,你通常想要比较字符串的文本内容而不是它们的指针,所以你应该使用-isEqualToString:方法NSString.此代码将返回,These strings are the same因为它比较字符串对象的值而不是它们的指针值:

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

要比较任意Objective-C对象,您应该使用更通用的isEqual:方法NSObject.-isEqualToString:-isEqual:您知道两个对象都是NSString对象时应该使用的优化版本.

- (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
          }
     }
}
Run Code Online (Sandbox Code Playgroud)