iOS KVO 学习笔记
//// //// main.m //// TestBasis //// //// Created by ficow on 16/1/14. //// Copyright © 2016年 ficow. All rights reserved. //// // #import <Foundation/Foundation.h> /////////////////////////////////////////////////////////////////////////////////////////////// @interface myClass1 : NSObject @property (nonatomic, copy) NSString *str; @end @implementation myClass1 @end /////////////////////////////////////////////////////////////////////////////////////////////// @interface myClass : NSObject { } @property (nonatomic, retain) myClass1 *item; @end @implementation myClass - (id)init{ if(self = [super init]){ [self setValue:[[myClass1 alloc]init] forKey:@"item"];//如果不给item设置值,则最后得到的item.str为空! } return self; } ///////////////////////////////////////////////////////////////////////////////////////////// //KVO part - (void) setItem:(myClass1 *)item{ _item = item; [self addObserver:self forKeyPath:@"item.str" options:NSKeyValueObservingOptionNew context:nil];//1.添加监听器,监听item.str //[self.item addObserver:self forKeyPath:@"str" options:NSKeyValueObservingOptionNew context:nil];和上面的效果一样 } //重写监听的方法,当被监听的对象改变了,就回调监听器的这个方法 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ NSLog(@"item.str has changed"); } - (void)dealloc{ [self removeObserver:self forKeyPath:@"item.str"];//用完就删除监听器 } @end ///////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, const char * argv[]) { @autoreleasepool { class1.item.str = @"item.str"; } return 0; }
Stay hungry,stay foolish.