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);}


8 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/ .
Perhaps, instead of complaining about missing a high-level crutch “language” like Ruby, you should just be a real programmer, and write your own regex library in a real low-level language like c… Oh yeah, you can’t.
Dang,
Someone took the corporate programmer route instead of following his dreams of working for himself. What level are you up to there chief?
BTW- I can
Really? That’s how you want to spend your day? Comparing schlongs and rewriting the wheel?