利用RunTime给Category增加属性并将Category中的值传给子类

一 利用runTime给Category增加属性,严格来说只是并不是真正的属性,只是C语言的set / get方法,但是调用时跟OC属性是一样调用的。

比如给UITableViewCell+MyStudent.h增加两个NSString类型的属性

在.h中这么写

#import 

@interface UITableViewCell (MyStudent)

@property (nonatomic, strong) NSString *stuName;

@property(nonatomic,strong) NSString *stuAge;

在.m中这么写

先import runtime

#import 
@interface UITableViewCell ()
@end

给两个属性两个key

@implementation UITableViewCell (MyStudent)

static const void *stuNameKey = &stuNameKey;
static const void *stuAgeKey = &stuAgeKey;


@dynamic stuName;
@dynamic stuAge;

runTime中的get方法

- (NSString *)stuName {
    return objc_getAssociatedObject(self, stuNameKey);
}

runTime中的set方法,注意set后面的属性首字母大写

- (void)setStuName:(NSString *)stuName{
    objc_setAssociatedObject(self, stuNameKey, stuName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

stuAge属性类似

- (NSString *)stuAge {
    return objc_getAssociatedObject(self, stuAgeKey);
}

- (void)setStuAge:(NSString *)stuAge{
    objc_setAssociatedObject(self, stuAgeKey, stuAge, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

二 在category中调用了函数后传值给子类。比如在列表中,每个tableViewCell都有一个倒计时的功能,并将倒计时的时间显示在cell上。

我在UITableViewCell+MqlClock分类中将倒计时的时间已经计算出来了
分类的.m中这么写

- (void)runCADisplayLinkTimer {
    计算时间
    [self showTheCountDownTime:计算出的时间];
}

- (void)showTheCountDownTime:(NSString *)time{

}

在CuntomTableViewCell.m中这么写

#import "UITableViewCell+MqlClock.h"

重载这个方法,参数就是传过来的值,有种代理的感觉

- (void)showTheCountDownTime:(NSString *)time{
    self.timeLable.text = time;
}

@end

你可能感兴趣的:(利用RunTime给Category增加属性并将Category中的值传给子类)