Objective-C has the great mechanism called Categories that gives you the ability to extend existing classes (like NSString, etc.) with your own methods. To get an easier way to check if a string starts with another string you can do:
@implementation NSString (CBAccessors)
- (BOOL) startsWith:(NSString*)str {
NSRange r = [self rangeOfString:str];
return r.location == 0 && r.length == [str length];
}
@end
You can then use that method as if it was always available (as long as you #include the header where that Category is declared):
if ([anyStringVariable startsWith:@"test"]) {…}
Please note that you should always give the new methods a prefix, to prevent issues with other Categories adding the same method or if Apple decides to add the method themselves (I removed my prefix here for readability).
But what would you do, if you need a utility method that does’n act on a given object. For example if you want to have a method, that shows an alert screen with a message. You may extend UIAlertView or add a method to your delegate. Both options look a bit like this, when called:
[UIAlertView showAlertViewWithTitle:@"Title"
andMessage:@"Message to display"];
That is nice and readable.
To get an even more compact code, you can build on the fact, that Objective-C is based on C. As many novice Objective-C developer might not know, you can easily integrate Objective-C and C code and build a compact C method for that:
void ShowAlertView(NSString *title, NSString *message) {
UIAlertView *alertView = [[UIAlertView alloc] initWith…. ];
[alertView show];
[alertView release];
}
Then you can show an alert view by:
ShowAlertView(@"Error", @"Downloading the whole internet failed");
The first solution is a bit more self-explanatory because the parameters are named.
There are other examples where a C function is useful. A nice example is a function to get the current language:
NSString *currentLanguage() {
static NSString *currentLanguage = nil;
if (!currentLanguage) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
currentLanguage = [languages objectAtIndex:0];
}
return currentLanguage;
}