标签:dynamic objc_setassociatedob 添加属性
通过@dynamic和objc_setAssociatedObject,实现给类别添加属性,前者说明:程序员手动实现setter和getter,后者则是动态给对象添加属性。两个配合使用可以实现给对象添加属性。
下面代码以scrollview为例,给scrollView添加一个refreshView属性,别的地方可以像正常属性一样使用refreshView:
【头文件】
@interface UIScrollView (Refresh) @property (nonatomic) RefreshView * refreshView; @end
【源文件】需要runtime头文件
#import <objc/runtime.h> static char kRefreshView; @implementation UIScrollView (Refresh) @dynamic refreshView; - (void)setRefreshView:(RefreshView *)aView { objc_setAssociatedObject(self, &kRefreshView, aView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (RefreshView *)refreshView { return objc_getAssociatedObject(self, &kRefreshView); } @end
给类别添加属性(通过@dynamic和objc_setAssociatedObject实现)
标签:dynamic objc_setassociatedob 添加属性
原文地址:http://blog.csdn.net/hherima/article/details/45070771