About KVC & KVO

KVC: Key value coding

其实就是另一种形式的 getter setter. 引用一段kenshicui博客中的介绍:

KVC的操作方法由NSKeyValueCoding协议提供,而NSObject就实现了这个协议,也就是说ObjC中几乎所有的对象都支持KVC操作,常用的KVC操作方法如下:

  • 动态设置:
    setValue:属性值 forKey:属性名(用于简单路径)
    setValue:属性值 forKeyPath:属性路径(用于复合路径,例如Person有一个Account类型的属性,那么person.account就是一个复合属性)
  • 动态读取:
    valueForKey:属性名 、valueForKeyPath:属性名(用于复合路径)

  • 这里的Key值是类中属性变量的字符串。例如:有一个DIY类,有一个属性变量
    @property (nonatomic,strong) NSArray *list;, 那么他的path就是@“”

KVC用在给readonly变量赋值!

//有一个类名为 ACLStudent,他有一 个@property (nonatomic, copy, readonly) NSString *firstName;
ACLStudent *student = [[ACLStudent alloc] init];

[student setValue:@"Qiu" forKey:NSStringFromSelector(@selector(firstName))];
NSLog(@"student firstName after changed: %@", student.firstName);

通过这种方式可以给他的readonly变量赋值

KVO Key value observe 重点说一下KVO

通过添加观测者,在指定的KEY发生改变/设定时,使用回调函数。如下:

  • 添加观察着用 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
  • 添加回调函数用-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
// 注册/添加观测者
-(void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"now KVO_View2 = %@",self.KVO_View2);
    self.KVO_View2 = @"Goat shit";
    
    [self addObserver:self
           forKeyPath:@"KVO_View2"
              options:NSKeyValueObservingOptionOld
              context:NULL];
}
//......中间其他代码省略......
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"KVO_View2"]) {
        NSLog(@"Current KVO_View2 = %@",self.KVO_View2);
        self.show.text = self.KVO_View2;
    }
}
  • 观察可变数组muatableArray的变化时候特别要注意的
    • 必须使用self.goodsInfoArray而不是_goodsInfoArray才行
    [self.goodsInfoArray addObject:goodsInfo];
    
    要替换成
    [[self mutableArrayValueForKey:@"goodsInfoArray"] addObject:goodsInfo];
    

才能监听到

  • 顺便提一下,MJRefresh的下拉刷新,就是用KVO去监听UIScrollViewcontent offsetY,当偏移量大于某一个值时,上面的frame下拉显示。

需要说明的几点是:

  1. 就目前来看,KVO多用于单个VC内部使用,用于多个VC跳转时会出现跳转过程,因为退出当前KV而KVO的observer没有remove而产生的错误
    'An instance 0x7faa81d0c290 of class ForKVOViewController was deallocated while key value observers were still registered with it.
  2. KVO的观测只是观察path上的至是否被设置,而不能知道他是否和旧的值相同
  3. 关于option的几个值说明(待以后补充)

NSKeyValueObservingOptionNew

Indicates that the change dictionary should provide the new attribute value, if applicable.

NSKeyValueObservingOptionOld

Indicates that the change dictionary should contain the old attribute value, if applicable.

NSKeyValueObservingOptionInitial

If specified, a notification should be sent to the observer immediately, before the observer registration method even returns.
The change dictionary in the notification will always contain an NSKeyValueChangeNewKey entry if NSKeyValueObservingOptionNew is also specified but will never contain an NSKeyValueChangeOldKey entry. (In an initial notification the current value of the observed property may be old, but it's new to the observer.) You can use this option instead of explicitly invoking, at the same time, code that is also invoked by the observer's observeValueForKeyPath:ofObject:change:context: method. When this option is used withaddObserver:forKeyPath:options:context: a notification will be sent for each indexed object to which the observer is being added.

NSKeyValueObservingOptionPrior

Whether separate notifications should be sent to the observer before and after each change, instead of a single notification after the change.
The change dictionary in a notification sent before a change always contains an NSKeyValueChangeNotificationIsPriorKey entry whose value is [NSNumber numberWithBool:YES], but never contains an NSKeyValueChangeNewKey entry. When this option is specified the change dictionary in a notification sent after a change contains the same entries that it would contain if this option were not specified. You can use this option when the observer's own key-value observing-compliance requires it to invoke one of the -willChange... methods for one of its own properties, and the value of that property depends on the value of the observed object's property. (In that situation it's too late to easily invoke -willChange... properly in response to receiving an observeValueForKeyPath:ofObject:change:context: message after the change.)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容