Http://www.davidhamrick.com/2012/02/12/Adding-Properties-to-an-Objective-C-Category.html
Let's say you have a category that needs to store some information. Unfortunately you can't add an instance variable, but you can add something called an associated reference. From the documentation:
Associative references, available starting in Mac OS X v10.6, simulate the addition of object instance variables to an existing class
To create an association you useobjc_setAssociatedObject
Function
And to retrieve an association useobjc_getAssociatedObject
Method.
Using an associated reference as storage for a property
We can use this technique to make a built in class have a property that we want. In this example, I am storing the name of a style that I want to assign to a uiview.
@interface UIView (DHStyleManager)@property (nonatomic, copy) NSString* styleName;@end
#import "UIViewDHStyleManager.h"NSString * const kDHStyleKey = @"kDHStyleKey";@implementation UIView (DHStyleManager)- (void)setStyleName:(NSString *)styleName{objc_setAssociatedObject(self, kDHStyleKey, styleName, OBJC_ASSOCIATION_COPY);}- (NSString*)styleName{return objc_getAssociatedObject(self, kDHStyleKey);}@end
When instances of uiview are released they will also release their associated references.
This technique let's use set this custom property on plain old uiviews. If you only need to do something simple like add a property, this provides a nice alternative to subclassing.
#import UIViewDHStyleManager.h"UIView* v = [[[UIView alloc] init] autorelease];v.styleName = @"someStyleName";NSLog(@"v = %@",v.styleName); //Logs 'someStyleName'