13

如何检查字典中的键是否与方法参数中的字符串相同?即在下面的代码中,dictobj 是 NSMutableDictionary 的对象,对于 dictobj 中的每个键,我需要与字符串进行比较。如何做到这一点?我应该键入 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
          }
     }
}
4

1 回答 1

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
          }
     }
}
于 2010-02-19T03:27:13.517 回答