我举了一些如何在 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];
我不明白为什么:-(
属性 range
和 rangeAtIndex
应由 NSTextCheckingResult
返回为 NSRange
而不是 id
.
有没有办法将 id 隐藏到 NSRange?
谢谢
最佳答案
我怀疑这里的问题一定是编译器找不到 range
和 rangeAtIndex:
方法的声明。由于它找不到它们,因此将它们的返回类型默认为id
。确保您已将带有这些方法声明的头文件导入到引用代码所在的文件中。或者您可能已导入该头文件,但它不包含声明,因此请确保您已提供它们
关于objective-c - NSTextCheckingResult范围返回 "id"而不是 "NSRange",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23806359/