Objective-C语法问题

时间:2010-05-25 07:31:16

标签: objective-c cocoa syntax nsstring

只是在搜索NSString中的字符或单词时进行了一些研究,我遇到了这段代码片段(就像魅力一样):

return [sourceString rangeOfString:searchString].location != NSNotFound;

我是否正确地认为上述代码在功能上与:

相同
NSRange range = [sourceString rangeOfString:searchString];
if (range.location == NSNotFound)
    return NSNotFound;
else
    return range.location;

显然第一个片段更清晰,但我不清楚!= NSNotFound部分。有人可以向我解释一下吗?

2 个答案:

答案 0 :(得分:9)

!=运算符求值为布尔值,因此它等效于:

NSRange range = [sourceString rangeOfString:searchString];
if (range.location == NSNotFound)
    return NO;
else
    return YES;

与以下内容相同:

NSRange range = [sourceString rangeOfString:searchString];
BOOL didNotFind = (range.location == NSNotFound);
return !didNotFind;

答案 1 :(得分:3)

实际上不,它相当于:

NSRange range = [sourceString rangeOfString:searchString];
if (range.location == NSNotFound)
    return NO;
else
    return YES;

可以写得更短:

NSRange range = [sourceString rangeOfString:searchString];
BOOL result = range.location != NSNotFound;
return result;