Creating traditional looking methods in Objective-C
Posted by Leonard Ah Kun in Coding Tricks, How-to, iOS
When new developers decide they want to learn Objective-C, at first glance it is quite intimidating. Mainly because of the method calling syntax that looks like this.
[awesomeObject doSomethingAwesomeWith:anotherAwesomeObject and:someOtherAwesomeObject with:awesomeness];
Although this format describes the method you calling better, it often feels a bit verbose when coding as it requires a lot more to type and a lot more to read. Sometimes you just want a quick method you can call to do things you do a lot.
Lets take the NSString object as an example. There are quite a few methods that I use a often, but always forget how to use them as the methods seem overcomplicated. What I do is create a header (.h) file with common tasks I do in a simpler method that can be called. This is an example some NSString methods I have in my collection.
//compare 2 strings
//index of a string found
static inline int CobiStringFind(NSString* string, NSString* subString) {
NSRange range = [string rangeOfString:subString];
if (range.location != NSNotFound) {
return range.location;
}
return -1;
}
//get last index of a string
static inline int CobiStringLastIndexOf(NSString* string, NSString *subString) {
NSRange range = [string rangeOfString:subString options:NSBackwardsSearch];
if (range.location != NSNotFound) {
return range.location;
}
return -1;
}
//get substring with start and end index
static inline NSString* CobiStringSubString(NSString* string, int startPos, int endPos) {
return [string substringWithRange:NSMakeRange(startPos, endPos-startPos)];
}
//append character to a string
static inline NSString* CobiStringAppendChar(NSString* string, unichar character) {
return [NSString stringWithFormat:@"%@%C",string,character];
}
This is quite useful for convenience methods you call a lot. For example if you create a method to translate hex formatted colors into a UIColor, instead of writing a method that looks like [UIColor colorFromHex:@"ffffff"]; you could write a method that looks like ColorFromHex(@”ffffff”); which I think is much easier to read and code with.


