利用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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容