KVO的基本概念
基本概念
键-值观察是一种使对象获取其他对象的特定属性变化的通知机制。
控制器层的绑定技术就是严重依赖键-值观察获得模型层和控制器层的变化通知的。对于不依赖控制器层类的应用程序,键-值观察提供了一种简化的方法来实现
检查器并更新用户界面值。
与 NSNotification不同,键-值观察中并没有所谓的中心对象来为所有观察者提供变化通知。取而代之地,当有变化发生时,通知被直接发送至处于观察状态的对
象。NSObject提供这种基础的键-值观察实现方法,你几乎不用重写该方法。
你可以观察任意对象属性,包括简单属性,对一或是对多关系。对多关系的观察者将会被告知发生变化的类型-也就是任意发生变化的对象。
键-值观察为所有对象提供自动观察兼容性。你可以通过禁用自动观察通知并实现手动通知来筛选通知。
注册观察者
为了正确接收属性的变更通知,观察对象必须首先发送一个addObserver:forKeyPath:options:context:消息至被观察对象,用以传送观察
对象和需要观察的属性的关键路径,以便与其注册。选项参数指定了发送变更通知时提供给观察者的信息。使用NSKeyValueObservingOptionOld选项可以将初始
对象值以变更字典中的一个项的形式提供给观察者。指定NSKeyValueObservingOptionNew选项可以将新的值以一个项的形式添加至变更字典。
你可以使用逐位“|”这两个常量来指定接收上述两种类型的值。
示例:
[child addObserver:self forKeyPath:@"tired"
options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
context:nil];
接收变更通知
接受变更通知
当监听的属性发生变动时,观察者收到一observeValueForKeyPath:ofObject:change:context:消息, 观察者必须实现这一方法。触发观察通知的对象和键路径、包含变更细节的字典,以及观察者注册时提交的上下文指针均被提交给观察者。
示例:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)c{
if ([keyPath isEqual:@"key"]) {
NSLog(@"");
}
}
移除观察者身份
你可以发送一条指定观察方对象和键路径的removeObserver:forKeyPath:消息至被观察的对象,来移除一个键-值观察者。(当我们达到目的时)
示例:
[child removeObserver:self forKeyPath:@"key"];
示例:
打开xcode
点击 create a new xcode project
点击 左侧 Application 选择右侧中的 Command Line Tool(相当于windows下的command)
--- next
product Name:KVODemo
Company identifier:com.imti
type: foundation 是一个framework
取消选择 use Automatic Reference Counting
--- next
--- create
new file...
name:Child
subclass: NSObject
Child.h
#import <Foundation/Foundation.h>
@interface Child : NSObject
@property(nonatomic,assign)NSInteger happyVal;
@end
Child.m
加入
- (id)init {
self = [super init];
if (self != nil) {
self.happyVal = 100;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
return self;
}
- (void)timerAction:(NSTimer *)timer {
self.happyVal--;
//当值发生改变就会触发监听事件调用observeValueForKeyPath方法 相当于一个事件
//赋值必须是.语法set 或者是kvc 进行设置
// _happyVal--; //error
// [self setValue:[NSNumber numberWithInteger:_happyVal] forKey:@"happyVal"];//ok
//注意_happyVal 要与 addObserver:self forKeyPath:@"happyVal" 中的 happyVal 保持一致
}
new file...
name:Nurse
subclass: NSObject
Nurse.h
#import <Foundation/Foundation.h>
@class Child;
@interface Nurse : NSObject
@property(nonatomic,retain)Child *child;
- (id)initWithChild:(Child *)child;
@end
Nurse.m
#import "Nurse.h"
#import "Child.h"
@implementation Nurse
- (id)initWithChild:(Child *)child {
self = [super init];
if (self != nil) {
_child = [child retain];//获得所有权
// self.child = child;
//注册一个观察者 观察属性happyVal的变化
//注册一个监听者 监听的属性为happyVal
//当happyVal值发生改变时会触发方法observeValueForKeyPath
[_child addObserver:self forKeyPath:@"happyVal"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:@"xxx"];
}
return self;
}
- (void)dealloc {
[_child removeObserver:self forKeyPath:@"happyVal"];
[_child release];
[super dealloc];
}
//keyPath-forKeyPath
//object -_child
// change- happyVal修改过的值
// context-context
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"%@",change);
}
main.m
加入
#import "Child.h"
#import "Nurse.h"
在加入
@autoreleasepool {
Child *child = [[Child alloc] init];
Nurse *nurse = [[Nurse alloc] initWithChild:child];
[[NSRunLoop currentRunLoop] run];
}
运行
课堂实例2:
修改之前的“大文件拷贝”作业,通过KVO监听已读的数据大小,实现拷贝的进度。
打开xcode
点击 create a new xcode project
点击 左侧 Application 选择右侧中的 Command Line Tool(相当于windows下的command)
--- next
product Name:FileCopyKVO
Company identifier:com.imti
type: foundation 是一个framework
取消选择 use Automatic Reference Counting
--- next
--- create
new file...
name:FileHandle 一个通用类可以给所有类使用进行文件的拷贝
subclass: NSObject
FileHandle.h
#import <Foundation/Foundation.h>
@interface FileHandle : NSObject {
@private
NSString *_srcPath; //源文件路径
NSString *_tagetPath; //目标文件路径
}
@property(nonatomic,assign)float filesize; //文件的总大小
@property(nonatomic,assign)float readedsize; //已读的数据大小
- (id)initPath:(NSString *)srcPath tagetPath:(NSString *)tagetPath;
- (void)startCopy;
@end
FileHandle.m
加入
- (id)initPath:(NSString *)srcPath tagetPath:(NSString *)tagetPath {
self = [super init];
if (self != nil) {
_srcPath = [srcPath copy];
_tagetPath = [tagetPath copy];
}
return self;
}
- (void)startCopy {
NSFileManager *fileManager = [NSFileManager defaultManager];
//创建目标文件
BOOL success = [fileManager createFileAtPath:_tagetPath contents:nil attributes:nil];
if (success) {
NSLog(@"create success");
}
//读取文件对象
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:_srcPath];
//写文件对象
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:_tagetPath];
//获取文件的属性
NSDictionary *fileAttri = [fileManager attributesOfItemAtPath:_srcPath error:nil];
//获取文件的大小
NSNumber *fileSizeNum = [fileAttri objectForKey:NSFileSize];
BOOL isEnd = YES;
self.filesize = [fileSizeNum longValue]; //文件的总大小
NSAutoreleasePool *pool = nil;
int n = 0;
NSLog(@"开始复制....");
while (isEnd) {
if (n % 10 == 0) {
[pool release];
pool = [[NSAutoreleasePool alloc] init];
}
//计算剩下未读文件的大小
NSInteger subLeng = self.filesize - _readedsize;
NSData *data = nil;
//如果剩余文件大小小于5000,则将剩下的数据全都读完,并且不再循环读取了
if (subLeng < 5000) {
isEnd = NO; //跳出循环
data = [inFile readDataToEndOfFile]; //读取剩下的数据
} else {
//读取5000个字节
data = [inFile readDataOfLength:5000];
//累加读取的大小
// _readedsize += 5000; 不会触发KVO
self.readedsize += 5000;
[inFile seekToFileOffset:_readedsize];
}
//写入数据
[outFile writeData:data];
n++;
}
//关闭文件
[outFile closeFile];
NSLog(@"文件复制成功");
}
new file...
name:User
subclass: NSObject
User.h
#import <Foundation/Foundation.h>
#import "FileHandle.h"
@interface User : NSObject {
@private
FileHandle *fileHandle;
}
- (void)doCopy;
@end
User.m
加入
- (id)init {
self = [super init];
if (self != nil) {
NSString *homePath = NSHomeDirectory();
NSString *srcPath = [homePath stringByAppendingPathComponent:@"svn配置.mov"];
NSString *tagetPath = [homePath stringByAppendingPathComponent:@"svn配置_bak.mov"];
fileHandle = [[FileHandle alloc] initPath:srcPath tagetPath:tagetPath];
//注册了属性的观察者
[fileHandle addObserver:self forKeyPath:@"readedsize" options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
- (void)doCopy {
[fileHandle startCopy];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"readedsize"]) {
NSNumber *readsizeNum = [change objectForKey:@"new"];
float readsize = [readsizeNum floatValue];
// fileHandle.filesize;
if ([object isKindOfClass:[FileHandle class]]) {
FileHandle *file = (FileHandle *)object;
float filesize = file.filesize;
float result = readsize/filesize * 100;//百分比
NSLog(@"%0.1f",result);
}
}
}
main.m
加入
#import "User.h"
在加入
@autoreleasepool {
User *user = [[User alloc] init];
[user doCopy];
}
运行
基本概念
键-值观察是一种使对象获取其他对象的特定属性变化的通知机制。
控制器层的绑定技术就是严重依赖键-值观察获得模型层和控制器层的变化通知的。对于不依赖控制器层类的应用程序,键-值观察提供了一种简化的方法来实现
检查器并更新用户界面值。
与 NSNotification不同,键-值观察中并没有所谓的中心对象来为所有观察者提供变化通知。取而代之地,当有变化发生时,通知被直接发送至处于观察状态的对
象。NSObject提供这种基础的键-值观察实现方法,你几乎不用重写该方法。
你可以观察任意对象属性,包括简单属性,对一或是对多关系。对多关系的观察者将会被告知发生变化的类型-也就是任意发生变化的对象。
键-值观察为所有对象提供自动观察兼容性。你可以通过禁用自动观察通知并实现手动通知来筛选通知。
注册观察者
为了正确接收属性的变更通知,观察对象必须首先发送一个addObserver:forKeyPath:options:context:消息至被观察对象,用以传送观察
对象和需要观察的属性的关键路径,以便与其注册。选项参数指定了发送变更通知时提供给观察者的信息。使用NSKeyValueObservingOptionOld选项可以将初始
对象值以变更字典中的一个项的形式提供给观察者。指定NSKeyValueObservingOptionNew选项可以将新的值以一个项的形式添加至变更字典。
你可以使用逐位“|”这两个常量来指定接收上述两种类型的值。
示例:
[child addObserver:self forKeyPath:@"tired"
options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
context:nil];
接收变更通知
接受变更通知
当监听的属性发生变动时,观察者收到一observeValueForKeyPath:ofObject:change:context:消息, 观察者必须实现这一方法。触发观察通知的对象和键路径、包含变更细节的字典,以及观察者注册时提交的上下文指针均被提交给观察者。
示例:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)c{
if ([keyPath isEqual:@"key"]) {
NSLog(@"");
}
}
移除观察者身份
你可以发送一条指定观察方对象和键路径的removeObserver:forKeyPath:消息至被观察的对象,来移除一个键-值观察者。(当我们达到目的时)
示例:
[child removeObserver:self forKeyPath:@"key"];
示例:
打开xcode
点击 create a new xcode project
点击 左侧 Application 选择右侧中的 Command Line Tool(相当于windows下的command)
--- next
product Name:KVODemo
Company identifier:com.imti
type: foundation 是一个framework
取消选择 use Automatic Reference Counting
--- next
--- create
new file...
name:Child
subclass: NSObject
Child.h
#import <Foundation/Foundation.h>
@interface Child : NSObject
@property(nonatomic,assign)NSInteger happyVal;
@end
Child.m
加入
- (id)init {
self = [super init];
if (self != nil) {
self.happyVal = 100;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
return self;
}
- (void)timerAction:(NSTimer *)timer {
self.happyVal--;
//当值发生改变就会触发监听事件调用observeValueForKeyPath方法 相当于一个事件
//赋值必须是.语法set 或者是kvc 进行设置
// _happyVal--; //error
// [self setValue:[NSNumber numberWithInteger:_happyVal] forKey:@"happyVal"];//ok
//注意_happyVal 要与 addObserver:self forKeyPath:@"happyVal" 中的 happyVal 保持一致
}
new file...
name:Nurse
subclass: NSObject
Nurse.h
#import <Foundation/Foundation.h>
@class Child;
@interface Nurse : NSObject
@property(nonatomic,retain)Child *child;
- (id)initWithChild:(Child *)child;
@end
Nurse.m
#import "Nurse.h"
#import "Child.h"
@implementation Nurse
- (id)initWithChild:(Child *)child {
self = [super init];
if (self != nil) {
_child = [child retain];//获得所有权
// self.child = child;
//注册一个观察者 观察属性happyVal的变化
//注册一个监听者 监听的属性为happyVal
//当happyVal值发生改变时会触发方法observeValueForKeyPath
[_child addObserver:self forKeyPath:@"happyVal"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:@"xxx"];
}
return self;
}
- (void)dealloc {
[_child removeObserver:self forKeyPath:@"happyVal"];
[_child release];
[super dealloc];
}
//keyPath-forKeyPath
//object -_child
// change- happyVal修改过的值
// context-context
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"%@",change);
}
main.m
加入
#import "Child.h"
#import "Nurse.h"
在加入
@autoreleasepool {
Child *child = [[Child alloc] init];
Nurse *nurse = [[Nurse alloc] initWithChild:child];
[[NSRunLoop currentRunLoop] run];
}
运行
课堂实例2:
修改之前的“大文件拷贝”作业,通过KVO监听已读的数据大小,实现拷贝的进度。
打开xcode
点击 create a new xcode project
点击 左侧 Application 选择右侧中的 Command Line Tool(相当于windows下的command)
--- next
product Name:FileCopyKVO
Company identifier:com.imti
type: foundation 是一个framework
取消选择 use Automatic Reference Counting
--- next
--- create
new file...
name:FileHandle 一个通用类可以给所有类使用进行文件的拷贝
subclass: NSObject
FileHandle.h
#import <Foundation/Foundation.h>
@interface FileHandle : NSObject {
@private
NSString *_srcPath; //源文件路径
NSString *_tagetPath; //目标文件路径
}
@property(nonatomic,assign)float filesize; //文件的总大小
@property(nonatomic,assign)float readedsize; //已读的数据大小
- (id)initPath:(NSString *)srcPath tagetPath:(NSString *)tagetPath;
- (void)startCopy;
@end
FileHandle.m
加入
- (id)initPath:(NSString *)srcPath tagetPath:(NSString *)tagetPath {
self = [super init];
if (self != nil) {
_srcPath = [srcPath copy];
_tagetPath = [tagetPath copy];
}
return self;
}
- (void)startCopy {
NSFileManager *fileManager = [NSFileManager defaultManager];
//创建目标文件
BOOL success = [fileManager createFileAtPath:_tagetPath contents:nil attributes:nil];
if (success) {
NSLog(@"create success");
}
//读取文件对象
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:_srcPath];
//写文件对象
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:_tagetPath];
//获取文件的属性
NSDictionary *fileAttri = [fileManager attributesOfItemAtPath:_srcPath error:nil];
//获取文件的大小
NSNumber *fileSizeNum = [fileAttri objectForKey:NSFileSize];
BOOL isEnd = YES;
self.filesize = [fileSizeNum longValue]; //文件的总大小
NSAutoreleasePool *pool = nil;
int n = 0;
NSLog(@"开始复制....");
while (isEnd) {
if (n % 10 == 0) {
[pool release];
pool = [[NSAutoreleasePool alloc] init];
}
//计算剩下未读文件的大小
NSInteger subLeng = self.filesize - _readedsize;
NSData *data = nil;
//如果剩余文件大小小于5000,则将剩下的数据全都读完,并且不再循环读取了
if (subLeng < 5000) {
isEnd = NO; //跳出循环
data = [inFile readDataToEndOfFile]; //读取剩下的数据
} else {
//读取5000个字节
data = [inFile readDataOfLength:5000];
//累加读取的大小
// _readedsize += 5000; 不会触发KVO
self.readedsize += 5000;
[inFile seekToFileOffset:_readedsize];
}
//写入数据
[outFile writeData:data];
n++;
}
//关闭文件
[outFile closeFile];
NSLog(@"文件复制成功");
}
new file...
name:User
subclass: NSObject
User.h
#import <Foundation/Foundation.h>
#import "FileHandle.h"
@interface User : NSObject {
@private
FileHandle *fileHandle;
}
- (void)doCopy;
@end
User.m
加入
- (id)init {
self = [super init];
if (self != nil) {
NSString *homePath = NSHomeDirectory();
NSString *srcPath = [homePath stringByAppendingPathComponent:@"svn配置.mov"];
NSString *tagetPath = [homePath stringByAppendingPathComponent:@"svn配置_bak.mov"];
fileHandle = [[FileHandle alloc] initPath:srcPath tagetPath:tagetPath];
//注册了属性的观察者
[fileHandle addObserver:self forKeyPath:@"readedsize" options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
- (void)doCopy {
[fileHandle startCopy];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"readedsize"]) {
NSNumber *readsizeNum = [change objectForKey:@"new"];
float readsize = [readsizeNum floatValue];
// fileHandle.filesize;
if ([object isKindOfClass:[FileHandle class]]) {
FileHandle *file = (FileHandle *)object;
float filesize = file.filesize;
float result = readsize/filesize * 100;//百分比
NSLog(@"%0.1f",result);
}
}
}
main.m
加入
#import "User.h"
在加入
@autoreleasepool {
User *user = [[User alloc] init];
[user doCopy];
}
运行