【问题标题】:NSTextCheckingResult range returns "id" instead of "NSRange"NSTextCheckingResult 范围返回“id”而不是“NSRange”
【发布时间】:2014-05-22 12:05:31
【问题描述】:

我举了一些如何在 Objective-c 中使用正则表达式的例子。 问题是我想对 Linux (gnustep) 和 OSX 使用相同的代码。 稍作改动后,它可以在 OSX 下运行,但在 Linux 下不行。

 NSArray* matches = [regex matchesInString:line options:0
                     range: NSMakeRange(0,[line length])];
     if ([matches count] > 0) {
        for (NSTextCheckingResult* match in matches) {
           NSString* matchText = [line substringWithRange:[match range]];
           NSLog(@"match: %@", matchText);
           NSRange group1 = [match rangeAtIndex:1];
           NSLog(@"group1: %@", [line substringWithRange:group1]);
        }
     }else{
        NSLog(@"nomatch %@",[matches count]);
     }

当我要编译这部分代码时编译器会返回错误:

错误:

sending 'id' to parameter of incompatible type 'NSRange' (aka 'struct _NSRange')
           NSString* matchText = [line substringWithRange:[match range]];

initializing 'NSRange' (aka 'struct _NSRange') with an expression of
                                              incompatible type 'id'
           NSRange group1 = [match rangeAtIndex:1];

我不明白为什么:-(

属性rangerangeAtIndex 应该由NSTextCheckingResult 返回为NSRange 而不是id

请问有没有办法将 id 转换为 NSRange?

谢谢

【问题讨论】:

    标签: objective-c gnustep


    【解决方案1】:

    我怀疑这里的问题一定是编译器找不到您的rangerangeAtIndex: 方法的声明。由于找不到它们,因此默认它们的返回类型为id。确保您已将带有这些方法声明的头文件导入到引用代码所在的文件中。或者你可能已经导入了那个头文件,但它不包含声明,所以请确保你已经提供了它们

    【讨论】:

    • 绝对正确!!!我把#import 放进去,一切都按我的预期工作。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多