KVO

作者: March_Cullen | 来源:发表于2017-03-08 21:47 被阅读0次
    • 让一个对象监听另一个对象属性的改变
    // MJPerson.h
    #import <Foundation/Foundation.h>
    @interface MJPerson : NSObject
    
    @property(nonatomic, assign)NSInteger age;
    
    @end
    
    // MJPerson.m
    @implementation MJPerson
    @end
    
    // MJDog.h
    #import <Foundation/Foundation.h>
    @interface MJDog : NSObject
    @end
    
    // MJDog.m
    #import “MJDog.h”
    @implementation MJDog
    @end
    
    // MJViewController.h
    #import <Foundation/Foundation.h>
    @interface MJViewController : UIViewController
    @end
    
    // MJViewController.m
    #import “MJViewController.h”
    #import “MJPerson.h”
    #import “MJDog”
    @interface MJViewController () // 这是类扩展,类别的一种
    
    @property (nonatomic, strong)MJPerson *person;
    @property (nonatomic, strong)MJDog *dog;
    
    @end
    
    @implementation MJViewController
    
    - (void)viewDidLoad {
      self.person = [[MJPerson alloc] init];
      self.dog = [[MJDog alloc] init];
      // 让self.dog监听self.person的age属性的改变
      [self.person addObsever:self.dog forKeyPath:@”age” options:0 context:nil];
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvents:(UIEvent *)event {
      self.person.age = 30;
    }
    
    @end
    

    KVO内部实现原理
    运行过程中,系统会自动生成一个NSKVONortifying_MJPerson :MJPerson类,调用person的setAge方法,会调用子类的setAge方法,runtime中会使用到KVO。

    // NSKVONortifying_MJPerson.h
    #import “MJPerson.h”
    @interface NSKVONortifying_MJPerson : MJPerson
    @end
    
    // NSKVONortifying_MJPerson.m
    #import “NSKVONortifying_MJPerson.h”
    @implementation NSKVONortifying_MJPerson
    
    - (void)setAge:(int)age {
      [super setAge:age];
      [self willChangeValueForKey:@”age”];
      [self didChangeValueForKey:@”age”];
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:KVO

          本文链接:https://www.haomeiwen.com/subject/jfsigttx.html