views:

132

answers:

2

Just doing some research on searching for a character or word within a NSString and I came across this code snippet (which works like a charm):

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

Am I right in thinking that the above code is functionally identical to:

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

Obviously the first snippet is much cleaner but I'm not clear on the != NSNotFound part. Could someone explain that to me?

+8  A: 

The != operator evaluates to a boolean, so it's equivalent to:

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

Which is the same as:

NSRange range = [sourceString rangeOfString:searchString];
BOOL didNotFind = (range.location == NSNotFound);
return !didNotFind;
Tom Dalling
Thanks - much clearer :-)
Garry
+3  A: 

Actually no, it's equivalent to:

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

Which can be written shorter as:

NSRange range = [sourceString rangeOfString:searchString];
BOOL result = range.location != NSNotFound;
return result;
calmh
You have to either compare using `!=` or return `!result` in the second version.
Georg Fritzsche
@georg Obviously. :) Corrected.
calmh