Tag Archives: extending

Some fun and magic with Objective-C categories

Categories are the way you can extend existing Objective-C class without subclassing. Even without having a source code of existing class.

Using categories you can add methods to existing classes (even to Foundation and UIKit classes). And you’ll be able to use them in your app. Also, you could replace existing methods with your implementation. But that’s not the topic of this tutorial. You should consult Apple documenation on categories for more information.

For example, let’s add a method to NSString to display it in alert.

@interface NSString (Alert)

-(void)showInAlert;

@end

Now we need to implement this method.

@implementation NSString (Alert)

-(void)showInAlert
{
    [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Debug", @"Debug title")
                                message:self
                               delegate:nil 
                      cancelButtonTitle:NSLocalizedString(@"Ok", @"Ok button title") 
                      otherButtonTitles:nil] show];
}

@end

Very simple. And now you can show any NSString as alert in your application.

- (IBAction)alertText
{
    [self.textField.text showInAlert];
}

Continue reading