【问题标题】:Comparing two strings through a selector: unexpected result通过选择器比较两个字符串:意外结果
【发布时间】:2012-07-19 21:52:56
【问题描述】:

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

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;
}

但它打印为零。为什么?

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

【问题讨论】:

    标签: objective-c automatic-ref-counting selector


    【解决方案1】:

    performSelector: 的文档声明 “对于返回除对象以外的任何内容的方法,请使用 NSInvocation”。 因为 caseInsensitiveCompare: 返回的是 NSInteger 而不是您需要创建的对象一个NSInvocation,涉及更多。

    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);
    

    【讨论】:

    • 很好的答案。只有一个问题:它可能返回 18446744073709551615 是正常的(比较 @"hello" 和 @"hell")?
    • 不,这不正常,你是怎么得到那个号码的?您复制并粘贴了我的代码,只是将其中的一个更改为hell?我得到的唯一值是10-1
    • 相同的代码,但只是格式错误:我确实写了 %lu 而不是 %d(以修复 xcode 警告)。将其更改为 %ld 并且可以正常工作。谢谢。跨度>
    • @RamyAlZuhouri %ld is correct, %lu 当数字为负数时会导致下溢,从而导致数字很大。
    【解决方案2】:

    试试

    NSString* str1=@"hello";
    NSString* str2=@"hello";
    
    if ([str1 caseInsensitiveCompare:str2] == NSOrderedSame)
                NSLog(@"%@==%@",str1,str2);
    else
                NSLog(@"%@!=%@",str1,str2);
    

    【讨论】:

    • 这应该是正确答案,因为它使用“比较”流程(NSOrderedSame、NSOrderedAscending、NSOrderedDescending)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多