Adding Properties to an Objective-C Category
来源:互联网 发布:雪豹特种部队 知乎 编辑:程序博客网 时间:2024/04/30 22:11
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'
- Adding Properties to an Objective-C Category
- Adding Properties to an Objective-C Category – Revisted
- An introduction to Objective-C Meta Class
- Objective-C使用Category
- Category 类别 -Objective-C
- Category 类别 -Objective-C
- Objective-C分类 (category)
- Category 类别 -Objective-C
- Objective-C相关Category
- Objective-C之category
- objective-c中的category
- Category 类别 -Objective-C
- Objective-C 分类Category
- Category 类别 -Objective-C
- objective-c category
- Objective-C之Category
- Objective-C:理解Category
- Objective-C之Category
- ... or one of its dependencies. The system cannot find the file specified... 加载指定dll失败
- 双线性内插值算法用于放大
- PHP用CURL伪造IP和来源
- STL源码之迭代器
- 'Times' 附近有语法错误
- Adding Properties to an Objective-C Category
- TC使用技巧——复制文件名及路径
- CMake生成VS2012 ARM project遇到的问题
- js调用打印当前页的两种方法
- 策略模式(Strategy) 4
- 笨鸟的数据结构理解 - 数组
- Adding Properties to an Objective-C Category – Revisted
- ubuntu设置开机启动图形应用程序,替换默认图形桌面
- 不用xib创建简单应用