iOS:OC在Category中使用@property定义属性

2016-05-15  本文已影响583人  斯文_7

有时候写Category需要@property定义属性。这个时候就需要使用@dynamic来进行修饰。
@dynamic是什么意思?
@dynamic修饰就是表明这个属性需要程序员自己管理该属性的setter和getter方法
这个时候就需要重写getter和setter方法了。

(简单粗暴)直接上代码

@interface UITableView (Extension) <TableViewDelegate>

@property (nonatomic, copy) NSString *name;

@end
#import "UITableView+Extension.h"

// 定义一个指针
static const void *Name = &Name;

@implementation UITableView (Extension)
@dynamic name;

- (void)setName:(NSString *)name {
    objc_setAssociatedObject(self, Name, name, OBJC_ASSOCIATION_COPY);
}

- (NSString *)name {
    return objc_getAssociatedObject(self, Name);
}

上一篇 下一篇

猜你喜欢

热点阅读