iOS底层原理总结--OC对象的分类:instance、class、meta-calss对象的isa和superclass - 掘金post
...atom
本文是根据 iOS底层原理总结-- KVO/KVC的本质 - 掘金 延展的一篇文章,因此获取的方法列表为添加kvo监听后,子类内部方法列表为例子。spa
请先浏览 iOS底层原理总结-- KVO/KVC的本质 - 掘金 文章后阅读本文。指针
代码会在 ( iOS底层原理总结-- KVO/KVC的本质 - KVO的代码实现 ) 此段代码的基础上进行更改,code
iOS底层原理总结-- KVO/KVC的本质 - KVO的代码实现orm
#import "ViewController.h"
#import "DLPerson.h"
#import <objc/runtime.h>
@interface ViewController ()
@property (nonatomic, strong) DLPerson *person1;
@property (nonatomic, strong) DLPerson *person2;
@end
@implementation ViewController
/** * 获取对象方法列表 */
- (void)printMethodNamesOfClass:(Class)cls{
unsigned int count;
/// 获取方法数组
Method *methodList = class_copyMethodList(cls, &count);
/// 存储方法名
NSMutableString *methodNames = [NSMutableString string];
/// 遍历全部的方法
for (int i = 0; i < count; i++) {
/// 获取方法
Method method = methodList[i]; /// 指针当作数组用。
NSString *methodName = NSStringFromSelector( method_getName(method));
[methodNames appendFormat:@"%@, ", methodName];
}
/// 释放 C语言须要释放
free(methodList);
/// 打印方法名
NSLog(@"%@ %@", cls, methodNames);
}
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[DLPerson alloc]init];
self.person1.age = 10;
self.person2 = [[DLPerson alloc]init];
self.person2.age = 1;
///> person1添加kvo监听
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person2 addObserver:self forKeyPath:@"age" options:options context:nil];
[self printMethodNamesOfClass: object_getClass(self.person1)];
[self printMethodNamesOfClass: object_getClass(self.person2)];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.person1 setAge:20];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"监听到了%@的%@属性发生了改变%@",object,keyPath,change);
}
- (void)dealloc{
///> 使用结束后记得移除
[self.person1 removeObserver:self forKeyPath:@"age"];
}
@end
复制代码
打印结果cdn
DLPerson setAge:, age,
NSKVONotifying_DLPerson setAge:, class, dealloc, _isKVOA,
复制代码
由打印结果可得出 当一个对象添加了KVO的监听时,当前对象的isa指针指向的就不是你原来的类,指向的是另一个类对象,以下图
第一行打印 为person1的方法列表,未添加KVO监听, isa直接指向的是DLPerson只有age的set和get方法
第二行打印 为person2的方法列表,person添加KVO监听后 isa指针指向的是NSKVONotifying_DLPerson CLass对象 方法列表包含了 delloc _isKVOA 和 setAge
... 持续更新