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

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

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

在.h中这么写

#import <UIKit/UIKit.h>

@interface UITableViewCell (MyStudent)

@property (nonatomic, strong) NSString *stuName;

@property(nonatomic,strong) NSString *stuAge;

在.m中这么写

先import runtime

#import <objc/runtime.h>
@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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容