1、不能在分类中添加实例变量的原因
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; // 协议列表
const struct _prop_list_t *properties; // 属性列表
};
因为分类的本质也是结构体,这里没有实例变量的列表,添加进去存不了。(个人理解)
2、实际操作检查的结果
1)创建分类的.h和.m文件
.h文件
#import "timerController.h"
NS_ASSUME_NONNULL_BEGIN
@interface timerController (timer)
@property(nonatomic,copy)NSString *time;
@end
.m文件(使用关联对象实现setter和getter方法)
-(NSString *)time
{
return objc_getAssociatedObject(self, _cmd);
}
-(void)setTime:(NSString *)time
{
objc_setAssociatedObject(self, @selector(time), time, OBJC_ASSOCIATION_COPY);
}
2)打印类的实例变量列表
- (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)打印结果
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---
从打印结果可以看出,time属性添加成功,getter和setter方法也实现了,touchesBegan方法点击也有响应,但是类的实例变量列表里没有_time。
网友评论