Objective-C Language Adding a property with a category


Properties can be added with categories using associated objects, a feature of the Objective-C runtime.

Note that the property declaration of retain, nonatomic matches the last argument to objc_setAssociatedObject. See Attach object to another existing object for explanations.

#import <objc/runtime.h>

@interface UIViewController (ScreenName)

@property (retain, nonatomic) NSString *screenName;


@implementation UIViewController (ScreenName)

@dynamic screenName;

- (NSString *)screenName {
    return objc_getAssociatedObject(self, @selector(screenName));

- (void)setScreenName:(NSString *)screenName {
    objc_setAssociatedObject(self, @selector(screenName), screenName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);