KVC 基础要点
//
// Foo.h
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Bar;
@interface Foo : NSObject
{
Bar *bar;
NSString *StringOnFoo;
}
@property (retain,nonatomic) Bar *bar;
@property(retain,nonatomic) NSString *stringOnFoo;
@end
//
// Bar.h
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Bar : NSObject
{
NSArray *_array;
NSString *_stringOnBar;
}
@property (retain,nonatomic) NSArray * array;
@property (retain,nonatomic) NSString * stringOnBar;
@end
Foo *foo = [[Foo alloc] init];
[foo setValue:@"哈哈" forKey:@"stringOnFoo"];
NSString *str = [foo valueForKey:@"stringOnFoo"];
NSLog(@"str1 value %@",str);
[foo setValue:@"my name is zhangsan" forKeyPath:@"bar.stringOnBar"];
NSString *str2 = [foo valueForKeyPath:@"bar.stringOnBar"];
NSLog(@"str2 value %@",str2);
/**键路径全名规则
1.键必须是ASCII编码,
2.键必须是小写字母开头,第一个字母可以是下划线,但不能是数字与大写字母
3.键不能包含空格
**/
/**
键路径中使用函数
函数只能在对象数组与对象集合中使用
用法:以@为前缀开头,后接函数名,一个"."符号以及要操作的属性
**/
// [anArrayOfProducts valueForKeyPath:@“@avg.price”]; 这行代码的意思是收集其中的每个对象的价格属性求平均值
// [anArrayOfProducts valueForKeyPath:@"@sum.cost"];
KVO
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
(新浪微博底部导航栏的红点数字变化就是根据KVO来实现的)
二,使用方法
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 移除观察
1.在需要观察的对象中添加观察者对象
2.说明在观察者对象的方法中,options,传入的可能 值有四种
NSKeyValueObservingOptionNew 作为变更信息的一部分发送新值
NSKeyValueObservingOptionNew 作为变更信息的一部分发送旧值
</pre><pre code_snippet_id="1570995" snippet_file_name="blog_20160131_10_6322436" name="code" class="objc">-(id) initWithPoint:(MyPoint *) inPoint
{
if (self = [super init]) {
point = inPoint;
//添加观察者对象
[point addObserver:self forKeyPath:@"x" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:NULL];
[point addObserver:self forKeyPath:@"y" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:NULL];
}
return self;
}
实现KVO的回调
/**
定义KVO的回调
**/
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
NSNumber *old = [change objectForKey:NSKeyValueChangeOldKey];
NSNumber *new = [change objectForKey:NSKeyValueChangeNewKey];
if (keyPath == @"x") {
NSLog(@"Value for X change from:%f to %f",[old floatValue],[new floatValue]);
}
if (keyPath == @"y") {
NSLog(@"Value for Y change from:%f to %f",[old floatValue],[new floatValue]);
}
}
移除观察者
-(void)dealloc
{
/**移除观察者***/
[point removeObserver:self forKeyPath:@"x"];
[point removeObserver:self forKeyPath:@"y"];
point = nil;
NSLog(@"do dealLoc");
}