检查在Objective-C的平等
-
21-09-2019 - |
题
如何检查在字典关键是相同方法参数的字符串? 即在下面的代码,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
}
}
}
解决方案
当您使用==
运算符,在比较指针值。这时候的对象时,比较是完全一样的对象,在相同的内存地址才有效。例如,该代码将返回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
}
}
}
不隶属于 StackOverflow