在Objective-C中检查是否相等 [英] Checking for equality in Objective-C

查看:158
本文介绍了在Objective-C中检查是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字典中的键与方法参数中的字符串相同? 即在下面的代码中,dictobj是NSMutableDictionary的对象,对于dictobj中的每个键,我需要与字符串进行比较.如何实现呢?我应该输入NSString的大小写键吗?

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
          }
     }
}

推荐答案

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

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 return These objects are different because although the strings are the same, they are stored at different locations in memory:

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

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

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 of NSString. This code will return These strings are the same because it compares the value of the string objects rather than their pointer values:

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对象,应使用NSObject的更通用的isEqual:方法. -isEqualToString:-isEqual:的优化版本,当您知道两个对象都是NSString对象时应使用.

To compare arbitrary Objective-C objects you should use the more general isEqual: method of NSObject. -isEqualToString: is an optimized version of -isEqual: that you should use when you know both objects are NSString objects.

- (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
          }
     }
}

这篇关于在Objective-C中检查是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆