iOS学习之KVO(一)

一,概述

KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

二,使用方法

系统框架已经支持KVO,所以程序员在使用的时候非常简单。

1. 注册,指定被观察者的属性,

2. 实现回调方法

3. 移除观察

三,实例:

1.新建Person类:

//

//  Person.h

//  KVOEx

//

//  Created by song on 12-11-19.

//  Copyright (c) 2012 song. All rights reserved.

//

 

#import

 

@interface Person : NSObject

{

    NSString* name;

    NSString* age;

}

@property(nonatomic,retain)NSString* name;

@property(nonatomic,retain)NSString* age;

@end

2.在ViewController的.m文件中写:

//

//  ViewController.m

//  KVOEx

//

//  Created by song on 12-11-19.

//  Copyright (c) 2012 song. All rights reserved.

//

 

#import "ViewController.h"

#import "Person.h"

@interface ViewController ()

 

@end

 

@implementation ViewController

@synthesize label;

@synthesize person;

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    person=[[Person alloc] init];

    [person setValue:@"KVO本来的值" forKey:@"name"];

    label=[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 120, 30)];

    label.textColor=[UIColor redColor];

    label.text=[person valueForKey:@"name"];

    [self.view addSubview:label];

    

    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];

    button.frame=CGRectMake(120, 150, 50, 30);

    [button setTitle:@">" forState:UIControlStateNormal];

    [button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

    [person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

    

    

}

 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;

{

    if ([keyPath isEqualToString:@"name"]) {

        label.text=[person valueForKey:@"name"];

//        [NSThread sleepForTimeInterval:2.0f];

 

    }

}

 

-(void)change:(id)sender

{

//    for (int i=0; i<10; i++) {

//        NSString* str=[NSString stringWithFormat:@"%d",i];

//        [person setValue:str forKey:@"name"];

//        NSLog(@"%d",i);

//    }

    [person setValue:@"改变KVO的值" forKey:@"name"];

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(void)dealloc

{

    [person release];

    [label release];

    [person removeObserver:self forKeyPath:@"name"];

    [super dealloc];

}

@end

转载于:https://www.cnblogs.com/swell/p/3487071.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值