2012-07-13 50 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