代码之家  ›  专栏  ›  技术社区  ›  suse

检查Objective-C中的相等性

  •  13
  • suse  · 技术社区  · 16 年前

    如何检查dictionary中的键是否与method参数中的字符串相同?

    -(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 回复  |  直到 16 年前
        1
  •  39
  •   Rob Keniger    16 年前

    当你使用 == 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");
    

    isEqual: 方法 NSObject . -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
              }
         }
    }