It’s times like this, that I miss ruby.
I’m checking a url to see if it has a substring. It would be so easy if this was ruby:
absolute_url.match(/my regex/).any?
In Objective C, you have to use rangeOfString which returns a range. If I were to run this on the string “the quick brown fox” with an argument of “brown” it would return {10,14}. If it’s not found, it would return {NSNotFound, 0}. Let’s use that to check to see if the range was found. We’ll use NSMakeRange to create the NSNotFound range and NSEqualRanges to compare them:
if(NSEqualRanges(NSMakeRange(NSNotFound, 0), [absoluteURL rangeOfString:@"my_substring"])){ NSLog(@"my_substring not found in absoluteURL %@", absoluteURL);}


5 Comments
Also can write this:
if([absoluteURL rangeOfString:@"my_substring"].location == NSNotFound)){
NSLog(@”my_substring not found in absoluteURL %@”, absoluteURL);
}
“It’s times like this, that I miss ruby.”
Only times like this?
I love my Mac, I love my iPhone, there are even parts of Cocoa that are nice, but there isn’t a moment I don’t wish that Objective C were just a little bit more like Python or Ruby.
Thanks! I’m an Objective-C and it took a lot of searching around to find out how to do this simple operation! My implementation seems to work the opposite of expectation, however. Strings containing the substring return the integer value of the substring’s location within the string being tested (deviceString) and the non-matches return 0×7fffffff. Given that, you’d thing the following snipped would require != to pass the test. I guess some things are not for man to know . . .
if([deviceString rangeOfString:@"tester"].location == NSNotFound)
[deviceStringArray addObject: deviceString];
well, I don’t understand your Ruby code…searching for a substring is just:
absolute_url[substring] #=> nil or the substring
but you’re absolutely right, the Objective-C APIs are sometimes pathetical…
If we want to be pedantic, perhaps the most idiomatic way to check for substring presence is to use the =~ operator, as in absolute_url =~ /my_regex/ .