kvo底层实现

```

- (void)AZ_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context{

NSString * newClassName = [@"azhi" stringByAppendingString:NSStringFromClass([self class])];

Class newClass =  objc_allocateClassPair([self class], newClassName.UTF8String, 0);

class_addMethod(newClass, @selector(setName:), (IMP)setName, "v@:@");

objc_registerClassPair(newClass);

object_setClass(self, newClass);

objc_setAssociatedObject(self, @"hehe", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

```

void setName(id self,SEL _cmd,NSString*name){

id observer = objc_getAssociatedObject(self, @"hehe");

objc_msgSend(observer, @selector(observeValueForKeyPath:ofObject:change:context:),@"name",self,@{@"new":name},nil);

id class = [self class];

object_setClass(self, [self superclass]);

objc_msgSend(self, @selector(setName:),name);

object_setClass(self, class);

}

```

你可能感兴趣的:(kvo底层实现)