給分類 Category 添加屬性铸董,首先要?jiǎng)?chuàng)建一個(gè)分類文件咸作,然后添加你要的屬性
.h 文件
?@property (strong, nonatomic, nullable) NSString * otherName;
重點(diǎn)來了!R虑恕K捕弧]锴亍!分類之所以不能添加是因?yàn)椴粫?huì)自動(dòng)生成setter 和getter 方法 在這里把這兩個(gè)方法添加上就可以了 然后需要用runtime添加上
.m 文件 ? ?導(dǎo)入??
//運(yùn)行時(shí)頭文件
#import<objc/runtime.h>
//給刷新控件設(shè)置 setter? getter 方法
static char * OtherNameKey = "OtherNameKey";
//運(yùn)行時(shí)實(shí)現(xiàn)getter方法
- (NSString *)otherName {
? ? //如果屬性值是非id類型盲再,可以通過屬性值先構(gòu)造OC的id對(duì)象西设,再通過對(duì)象獲取非id類型屬性
? ? return objc_getAssociatedObject(self, OtherNameKey);
}
//運(yùn)行時(shí)實(shí)現(xiàn)setter方法
- (void)setOtherName:(NSString*)otherName{
? ? objc_setAssociatedObject(self, OtherNameKey, otherName, OBJC_ASSOCIATION_RETAIN);
}
完事!4鹋蟆4俊!C瓮搿禽绪!