iOS中的KVC与KVO

来源:互联网 发布:淘宝如何在游戏平台 编辑:程序博客网 时间:2024/05/16 09:14

一、对于KVC模式(Key Value Coding)(http://my.oschina.net/caijunrong/blog/510701):

1、其实在实际开发中用得比较多得就是:接收到json数据之后,通过解析,解析成NSDictionary,然后再把字典对应的字段建立一个Model,在Model里面自定义一个类方法+(instancetype)modelWithDictionary:(NSDictionary *)keyDictionary方法中调用从而达到我们想要的效果,将字典装成Model。


 setValuesForKeyWithDictionary 方法


2、然后对于一些想要特殊处理的字段可以调用以下方法来进行特殊处理,比如里面有些key是字典类型,则可以通过以下方式搞定:

-(void) setValue:(id)value forKey:(NSString *)key {   if([key isEqualToString:@"products"])   {     for(NSMutableDictionary *productDict in value)     {       Prodcut *product = [[Product alloc] initWithDictionary:prodcutDict];       [self.products addObject:product];     }   } }



3、还有一种情况,就是里面的Key压根就没定义,可以通过重写以下这个方法来重新把key和value对应上号:

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {     if([key isEqualToString:@"nameXXX"])         self.name = value;     if([key isEqualToString:@"ageXXX"])         self.age = value;     else         [super setValue:value forKey:key]; }



二、对于KVO设计模式(KVO的简单使用):

Key Value Observing, 是一种observer 模式用于监听属性的变化

用addObserver:forKeyPath:options:context:去start observer

用removeObserver:forKeyPath:context去stop observer

回调就是observeValueForKeyPath:ofObject:change:context:。

KVO 的实现也依赖于 Objective-C 强大的 Runtime 。

以下是对于KVO的实验操作 storyboard已截图


////  ViewController.m//  WebTest////  Created by Tree on 16/2/26.//  Copyright © 2016年 Tree. All rights reserved.//#import "ViewController.h"#import "DataModel.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UILabel *TextLabel;@property (nonatomic, strong) DataModel *data;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];            DataModel *data = [[DataModel alloc] init];        [data setValue:@"KVO 初始化" forKey:@"labelText"];        [data addObserver:self forKeyPath:@"labelText" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];        self.data = data;        self.TextLabel.text = [data valueForKey:@"labelText"];}- (IBAction)addBtnDidClick:(id)sender {        [self.data setValue:@"KVO测试成功" forKey:@"labelText"];    }- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{    if ([keyPath isEqualToString:@"labelText"]) {                self.TextLabel.text = [self.data valueForKey:@"labelText"];            }}- (void)dealloc{        [self removeObserver:self forKeyPath:@"labelString"];}@end


0 0
原创粉丝点击