您的位置:首页 > 其它

浅析键值观察(KVO)的使用技巧

2015-12-22 14:14 197 查看
一,

以前看了好多的关于kvo的博客 今天自己使用了一下写个自己的一些心得吧,高手勿喷哦。

二,

相信使用kvo的同学们 都知道kvo的代表含义 在这里我就不在啰嗦了,下面直接代码演示一下。



创建一个People对象

.h文件

@interface People :NSObject

@property(nonatomic ,copy)NSString *name;

@property(nonatomic ,assign)int age;
+(People *)initSelf;

.m文件

static
People *people;

+(People *)initSelf

{

if (!people) {

people= [[Peoplealloc]init];

}

return
people;

}

使用

#import "ViewController.h"

#import "People.h"

@interface
ViewController ()
{
People *people;
NSArray *array;
int index;
}

@end

@implementation ViewController
staticNSString *name =@"name";
staticNSString *age =@"age";
- (void)viewDidLoad {

[superviewDidLoad];

array =@[@"wangsong",@"王松",@"ws"];

[selfcreatPeople];

}
- (IBAction)click:(id)sender {
if (index ==3) {
index =0;
}

[people
setValue:array[index]forKey:name];
index ++ ;
}

- (void)creatPeople
{

people = [PeopleinitSelf];

[peoplesetValue:@"王松"forKey:name];

[peoplesetValue:@"25"forKey:age];

//创建一个观察

[people
addObserver:self
forKeyPath:name
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:(__bridgevoid
*)([selfclass])];

//相信同学们都看出来了,context是一个标示,用途 在后面在给大家解释

}

//用于监听属性变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary
*)change context:(void *)context
{
//在这里要跟同学们详细说一下,if中的这些限制是为了,防止中断父类的监听被打断,和监听自己想要dui xia
if (object ==people && [keyPathisEqualToString:name]
&& context == (__bridgevoid *)([selfclass])) {
NSString *newName = [objectvalueForKey:name];
NSLog(@"-----%@",newName);
NSLog(@"++lod+++%@",change[@"new"]);
NSLog(@"new>>>>%@",change[@"new"]);
}
else
{
[superobserveValueForKeyPath:keyPathofObject:objectchange:changecontext:context];
}
}
- (void)dealloc
{
//防止移除父类的监听事件,而防止的标示就是context,

[peopleremoveObserver:selfforKeyPath:namecontext:(__bridgevoid
*)([selfclass])];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: