2012-07-13 48 views
1

我在做一个练习来学习如何在Objective-C中使用选择器。
在这段代码中,我试图比较两个字符串:通过选择器比较两个字符串:意外的结果

int main (int argc, const char * argv[]) 
{ 
    @autoreleasepool 
    { 
     SEL selector= @selector(caseInsensitiveCompare:); 
     NSString* [email protected]"hello"; 
     NSString* [email protected]"hello"; 
     id result=[str1 performSelector: selector withObject: str2]; 
     NSLog(@"%d",[result boolValue]); 
    } 
    return 0; 
} 

但它打印zero.Why?

编辑:
如果我将str2更改为@“hell”,我得到一个EXC_BAD_ACCESS。

回答

6

的文档performSelector:状态“对于返回以外的任何其他对象,请使用NSInvocation的方法”。由于caseInsensitiveCompare:返回一个NSInteger而不是一个对象,您将需要创建一个涉及更多的NSInvocation

NSInteger returnVal; 
SEL selector= @selector(caseInsensitiveCompare:); 
NSString* [email protected]"hello"; 
NSString* [email protected]"hello"; 

NSMethodSignature *sig = [NSString instanceMethodSignatureForSelector:selector]; 
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; 
[invocation setTarget:str1]; 
[invocation setSelector:selector]; 
[invocation setArgument:&str2 atIndex:2]; //Index 0 and 1 are for self and _cmd 
[invocation invoke];//Call the selector 
[invocation getReturnValue:&returnVal]; 

NSLog(@"%ld", returnVal); 
+0

尼斯answer.Just一个问题:是正常的,它可能会返回18446744073709551615(比较@“你好”和@“地狱”)? – 2012-07-13 21:23:52

+0

不,这是不正常的,你是如何得到这个数字?你复制并粘贴了我的代码,然后将其更改为'hell'?我得到的唯一值是'1','0'和'-1'。 – Joe 2012-07-13 21:25:29

+0

相同的代码,但只是它的格式错误:我写了%lu而不是%d(修复xcode警告)。将它更改为%ld并且它可以正常工作。谢谢。 – 2012-07-13 21:33:24

1

尝试

NSString* [email protected]"hello"; 
NSString* [email protected]"hello"; 

if ([str1 caseInsensitiveCompare:str2] == NSOrderedSame) 
      NSLog(@"%@==%@",str1,str2); 
else 
      NSLog(@"%@!=%@",str1,str2); 
+0

这应该是正确的答案,因为它使用了“比较”流(NSOrderedSame,NSOrderedAscending,NSOrderedDescending) – 2014-08-13 21:36:40