问题
I am doing an exercise to learn how to use selectors in Objective-C.
In this code I am trying to compare two strings:
int main (int argc, const char * argv[])
{
@autoreleasepool
{
SEL selector= @selector(caseInsensitiveCompare:);
NSString* str1=@"hello";
NSString* str2=@"hello";
id result=[str1 performSelector: selector withObject: str2];
NSLog(@"%d",[result boolValue]);
}
return 0;
}
But it prints zero.Why?
Edit:
And if I change str2 to @"hell" I get an EXC_BAD_ACCESS.
回答1:
The documentation for performSelector: states "For methods that return anything other than an object, use NSInvocation". Since caseInsensitiveCompare: returns an NSInteger instead of an object you will need to create an NSInvocation, which is more involved.
NSInteger returnVal;
SEL selector= @selector(caseInsensitiveCompare:);
NSString* str1=@"hello";
NSString* str2=@"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);
回答2:
try
NSString* str1=@"hello";
NSString* str2=@"hello";
if ([str1 caseInsensitiveCompare:str2] == NSOrderedSame)
NSLog(@"%@==%@",str1,str2);
else
NSLog(@"%@!=%@",str1,str2);
来源:https://stackoverflow.com/questions/11477951/comparing-two-strings-through-a-selector-unexpected-result