Adding Properties to an Objective-C Category

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值