开发中,我们都知道可以在分类中给类添加方法,但是不能直接添加属性字段,但是有时候在分类中我们确实需要添加属性字段,可以利用运行时添加。只需要重写属性的setter和getter就可以了。我应用的场景是该属性只用于分类中使用,在其他类中声明有点与分类使用脱节,而且代码混乱,所以添加到分类中。
首先在.h文件中声明属性
@interface MyVC (CustomMessage)
//声明属性
@property(nonatomic, strong) NSDate * moveTime ;
@end
然后在.m中进行setter和getter的重写
@implementation MyVC(CustomMessage)
@dynamic moveTime;
staticchar * moveTimeKey ="moveTimeKey";
#pragmamark - Setter && Getter
- (void)setMoveTime:(NSDate*) moveTime{
objc_setAssociatedObject(self, moveTimeKey, moveTime, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSDate*) moveTime{
id moveTime = objc_getAssociatedObject(self, moveTimeKey);
if(moveTime){
return moveTime;
}else{
//如果没有就返回昨天,让第一次移动生效
return [NSDate jk_dateYesterday];
}
}