KVO整理总结

本文介绍如何在iOS开发中使用KVO(Key-Value Observing)来观察Model的变化,并在ViewController中实现相应的响应机制。通过一个简单的示例,演示了如何设置观察者以及如何在属性变化时触发特定的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于KVO工程中用到不到,在此整理备份,以备以后使用

监制观察,即让某个VC成为某个Model的某个值的观察者,当该Model的该值发生变化时,会自动通知该VC,触发相应的方法,比较方便,在某些设计模式中常用。代码如下:


Model中:

@interface Student : NSObject
@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSString * score;
@end

VC中:

#import "ViewController.h"
#import "Student.h"

#define OBSERVER_KEY @"score"

@interface ViewController ()
@property (nonatomic, strong) Student * student;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    
    
    self.student = [[Student alloc] init];
    self.student.name = @"xiaoming";
    self.student.score = @"80";
    
    [self.student addObserver:self forKeyPath:OBSERVER_KEY options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    NSLog(@"keyPath == %@,\nchange == %@",keyPath,change);
    NSLog(@"student name == %@,score == %@,intScore == %ld",self.student.name,self.student.score,self.student.intScore );
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSString * newScore = [NSString stringWithFormat:@"%ld",(NSUInteger)arc4random()%100];
    self.student.score = newScore;
}

- (void)dealloc{
    [self.student removeObserver:self forKeyPath:OBSERVER_KEY context:nil];
}

代码很简单,备份。

详细介绍:

http://lib.youkuaiyun.com/article/ios/53438

http://www.tuicool.com/articles/zeqEFbR

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值