1唆铐、不能在分類中添加實(shí)例變量的原因
struct _category_t {
const char *name;
struct _class_t *cls;
const struct _method_list_t *instance_methods; // 對象方法列表
const struct _method_list_t *class_methods; // 類方法列表
const struct _protocol_list_t *protocols; // 協(xié)議列表
const struct _prop_list_t *properties; // 屬性列表
};
因?yàn)榉诸惖谋举|(zhì)也是結(jié)構(gòu)體哲戚,這里沒有實(shí)例變量的列表,添加進(jìn)去存不了或链。(個人理解)
2惫恼、實(shí)際操作檢查的結(jié)果
1)創(chuàng)建分類的.h和.m文件
.h文件
#import "timerController.h"
NS_ASSUME_NONNULL_BEGIN
@interface timerController (timer)
@property(nonatomic,copy)NSString *time;
@end
.m文件(使用關(guān)聯(lián)對象實(shí)現(xiàn)setter和getter方法)
-(NSString *)time
{
return objc_getAssociatedObject(self, _cmd);
}
-(void)setTime:(NSString *)time
{
objc_setAssociatedObject(self, @selector(time), time, OBJC_ASSOCIATION_COPY);
}
2)打印類的實(shí)例變量列表
- (void)viewDidLoad {
[super viewDidLoad];
self.time = @"this is test";
NSLog(@"----%@",self.time);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"---touchesBegan---");
unsigned int count;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar iva = ivars[i];
NSString *nameSTR = [NSString stringWithCString:ivar_getName(iva) encoding:NSUTF8StringEncoding];
NSLog(@"---->>>%@",nameSTR);
}
}
3)打印結(jié)果
2021-09-19 18:02:24.195602+0800 test2021913[54696:5234312] ----this is test
2021-09-19 18:02:26.109386+0800 test2021913[54696:5234312] ---touchesBegan---
2021-09-19 18:02:27.058011+0800 test2021913[54696:5234312] ---touchesBegan---
2021-09-19 18:02:27.386368+0800 test2021913[54696:5234312] ---touchesBegan---
2021-09-19 18:02:27.796677+0800 test2021913[54696:5234312] ---touchesBegan---
從打印結(jié)果可以看出,time屬性添加成功澳盐,getter和setter方法也實(shí)現(xiàn)了祈纯,touchesBegan方法點(diǎn)擊也有響應(yīng),但是類的實(shí)例變量列表里沒有_time叼耙。