检查Objective-C中的相等性

时间:2010-02-19 03:22:09

标签: 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
          }
     }
}

1 个答案:

答案 0 :(得分: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");

比较字符串时,您通常希望比较字符串的文本内容而不是指针,因此您应使用-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");

要比较任意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
          }
     }
}