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 use the objc_setAssociatedObject
function and to retrieve an association use theobjc_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'