Comparing two strings through a selector: unexpected result

两盒软妹~` 提交于 2019-12-11 09:42:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!