DISCLAIMER: This post describes APIs which reference internal methods and could be considered as private API and, therefore, apps could be rejected by Apple’s App Store review team. There is even a special message from Apple to avoid using these techniques in production apps.
There are situations when you want to understand more how your code works. So, you might be interested in getting all the information about particular class, including its instance variables, private methods and so on. There is even one particular reason, you might do that – to avoid accidentally overriding internal methods.
So, let’s create a method which will describe any object. We’re looking for output similar to regular class declaration.
@interface OurClass : ParentClass <Protocols...>
// instance variables
// properties, class and instance methods
This declaration will contain definition of all derived methods, variables, including private ones.
Rarely iOS and OS X developers might need to do initialization before their class is used. This might be called as “static constructors” in other development paradigms. Objective-C runtime also offers similar mechanisms which we will discuss in this topic.
NSObject class defines two class methods responsible for class initialization:
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)
Now we need to implement this method.
@implementation NSString (Alert)
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Debug", @"Debug title")
cancelButtonTitle:NSLocalizedString(@"Ok", @"Ok button title")
Very simple. And now you can show any
NSString as alert in your application.