键值监听KVO机制

为了满足数据模型组件的状态数据发生改变时,试图组件能够动态的更新自己,能够及时的显示数据模型组件更新后数据。

KVO键值监听机制的提出:

KVO机制由NSKeyValueObserving协议提供,NSObject遵守该协议。

注册监听器的方法:

(1)注册一个监听器,用于监听指定的key路径:addObserver:forKeyPath:optinos:context:

(2)根据key路径删除指定的监视器:removeObserver:forKeyPath:

(3)根据key路径删除指定的监视器,多了一个context参数removeObserver:forKeyPath:context:

重写:

observerValueForKeyPath:ofObject:change:context:方法,当数据模型组件的Key路径发生改变时,作为监视器的视图组件将会被激发,激发时就会回调监听器自身。重写该方法就可以得到最新的数据。


KVO编程的步骤:

(1)为被监听对象注册监听器,通常是数据模型组件

(2)重写监听器的observerValueForKeyPath:ofObject:change:context:方法。


简单测试:

FKUser.h

#import <Foundation/Foundation.h>

@interface FKUser : NSObject
@property (nonatomic,copy)NSString* name;

@end


FKUser.m

#import "FKUser.h"

@implementation FKUser
@synthesize name;
@end


FKItemView.h

#import <Foundation/Foundation.h>
#import "FKUser.h"

@interface FKItemView : NSObject
@property(nonatomic)FKUser* item;

-(void) showItemInfo;
@end


FKItemView.m

#import "FKItemView.h"

@implementation FKItemView
@synthesize item;

-(void)showItemInfo
{
    NSLog(@" %@ ",self.item.name);
}


-(void) setItem:(FKUser *)items
{
    self.item = items;
    
    [self.item addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
    
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"***********88*******");
    NSLog(@"KeyPath : %@ ",keyPath);
    NSLog(@"class : %@ ",object);
    NSLog(@"name : %@ ",[change objectForKey:@"new"]);
    
    NSLog(@" %@ ",context);
}


-(void)dealloc
{
    [self.item removeObserver:self forKeyPath:@"name"];
}


@end


#import <Foundation/Foundation.h>
#import "FKUser.h"
#import "FKItemView.h"


int main (int argc, const char * argv[])
{


    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        FKUser* user = [[FKUser alloc] init];
        
        user.name = @"zhang";
        
        FKItemView* userItem = [[FKItemView alloc] init];
        
        userItem.item = user;
        [userItem showItemInfo];
        
        user.name = @"xue";
        
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值