KVC和KVO

KVC和KVO
今天在这里给大家详解一下KVC和KVO的用法, 在这里首先给大家介绍一下KVC的用法,虽然他俩看似只差一个字母但,但其实两种放法的机制相差很大,千万不要被表象所蒙骗哦, 下面分别介绍了两种机制的使用方式, 理解之后你就明白, 他俩一毛钱关系也没有哦 ^- -^
KVC
KVC(键值编码,是KeyValue Coding的简称),它是一种可以直接通过字符串的名字(key)来访问类属性的机制.使用该机制不需要调取实例变量就可以访问对象属性,并对属性进行赋值.在iOS开发中, KVC经常会被使用,在给Model类进行赋值时,你会经常用到KVC, 如果你还不知道Model,请自行补习.下面的实例清单会涉及Model类.

实例清单1.1 KVC的最基础用法(setValue:forKey:):

//Person类.h文件内容
#import <Foundation/Foundation.h>
@class Student;
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end
//VC中.m内容

Person *per = [[Person alloc] init];
    [per setValue:@"火星人" forKey:@"name"];
    NSLog(@"%@", per.name);

实例清单1.2 KVC的第二种用法(setValuesForKeysWithDictionary:):

#import <Foundation/Foundation.h>
@interface Person : NSObject
// 自定义Model(Person)类.h文件内容/此.m文件无内容(在真正的开发中.m中是有内容, 在这里为了减少我的工作量,我lazy一下)

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic, strong) NSString *address;
@end
// VC中的.m文件中内容
// 定义一个字典, 在这里请注意,字典中Key值要和Model类中属性名一致,不然会出现问题,把出错的话,就复制粘贴吧! (^-#-^)
NSDictionary *personDic = @{@"name" :@"你是谁", @"phoneNumber" :@"1314512521", @"address" :@"国际空间站"};
    Person *per = [[Person alloc] init];
    
//注意:这只是KVC中的一种用法(下面会把中的用法都介绍一下)
    [per setValuesForKeysWithDictionary:personDic];

实例清单1.3 KVC的第三种用法(可能会失效,原因未知, 有待读者研究)(setValue:forKeyPath:):

// Person.h类文件
#import <Foundation/Foundation.h>
@class Student;
@interface Person : NSObject
@property (nonatomic, strong) Student *stu;
@end

// Student.h类文件  
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, strong) NSString *sex;
@end

//vc.m文件
#import "ViewController.h"
#import "Person.h"
#import "student.h"
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    Person *per = [[Person alloc] init];
    
    //关键路径赋值
    [per setValue:@"male" forKeyPath:@"stu.sex"];
    Student *stu = [[Student alloc] init];
    NSLog(@"%@", stu);
}

KVO
重点来了,KVO的时间到了,KVO的全称叫(Key-value observing),在我理解看来,就是一种监听机制,能够实时的监听关键Key值得变化,现在你可能不明白这个Key到底是神魔玩意, 先不要着急,继续读下去,在这我先举几个例子,比如:UIscrollView中属性contentOffset, 自定义的BOOL属性, UIView及子类的backgroundColor属性等等都可以作为Key,即观察的对象.废话不多说了,实例才能证明一切.
声明:如果想实现下列清单中的案例请粘贴到工程中就可以了,具体的实现可能使你更加的了解KVO -%-

实例清单如下:

//自定义的TitleView(网易新闻的文字横条)

//TitleView.h文件
#import <UIKit/UIKit.h>
@interface TitleView : UIView
@property (nonatomic, retain) NSArray *titles;
@end

//TitleView.m文件
#import "TitleView.h"
@interface TitleView ()
@end
@implementation TitleView
#pragma mark - override
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubviews];
    }
    return self;
}

- (void)setTitles:(NSArray *)titles {
    for (int i = 0; i < 5; i++) {
        [self.subviews[i] setTitle:titles[i] forState:UIControlStateNormal];
    }
}

- (void)createSubviews {
    for (int i = 0; i < 5; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];      
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        button.frame = CGRectMake(CGRectGetWidth(self.bounds) / 5 * i, 0, CGRectGetWidth(self.bounds) / 5, CGRectGetHeight(self.bounds));
        [self addSubview:button];
    }
}
// 当然自定义TitleView不是重点啦, 重点来啦
@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource,
UIScrollViewDelegate>

@property (nonatomic, retain) UIView *viewOfRedline;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) TitleView *viewOfTitle;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createViewOfRedLine];
    [self createCollectionView];
    [self createTitleView];
}

//不是重点哦
- (void)createViewOfRedLine {
    self.viewOfRedline = [[UIView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.bounds) / 5, 2)]; 
    [self.view addSubview:self.viewOfRedline];
    self.viewOfRedline.backgroundColor = [UIColor redColor];
}

// 不是重点哦
- (void)createCollectionView { 
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; 
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 66);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 66, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 66) collectionViewLayout:layout];
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    
    // 注册cell
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"pool"];
    self.collectionView.pagingEnabled = YES;
    
// KVO 观察collectionView的offset //注意:次步是重点 
    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];    
}

// 不是重点
- (void)createTitleView {
    self.viewOfTitle = [[TitleView alloc] initWithFrame:CGRectMake(0, 32, CGRectGetWidth(self.view.bounds), 32)];
    self.viewOfTitle.titles = @[@"头条", @"热点", @"财经", @"新闻", @"汽车"];  
    [self.view addSubview:self.viewOfTitle]; 
}

// KOV的实现,事件处理都在这里进行处理, 这是重点哦, 好好理解一下吧
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {

//objectForKey:@"new" 中的只能写@"new"(新的值, 监听的Key的变化的值) 或者写 @"old"(旧的值, 监听Key变化之前的值)
// 在这里我们获取新值(变化后的值)
    CGFloat x = [[change objectForKey:@"new"] CGPointValue].x / 5.0f;
    self.viewOfRedline.frame = CGRectMake(x, 64, CGRectGetWidth(self.view.bounds) / 5, 2); 
}

// UIScrollView的协议方法之一
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 5;
}

// UIScrollView的协议方法之一
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random() % (256) / 255.0f green:arc4random() % (256) / 255.0f blue:arc4random() % (256) / 255.0f alpha:1]; 
    return cell;
}

 // 改变标题的颜色
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = scrollView.contentOffset.x / 5.0f / (CGRectGetWidth(self.view.bounds) / 5);
    for (UIButton *button in self.viewOfTitle.subviews) {
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    [self.viewOfTitle.subviews[index] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];    
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 概念 先来看看概念,Key-value coding (KVC) 和 key-value observing (K...
    wuwy阅读 1,142评论 0 1
  • 目录:1.KVC用法;2.KVC和对象的setter、getter方法的区别;3.key和keyPath的区别;4...
    伦伦子_f7b3阅读 511评论 0 1
  • 什么是KVC和KVO?两者之间有何关系 KVC : 键值编码,是Key Value Coding 的简称,coco...
    兰章海晏阅读 3,430评论 0 3
  • 在编程中,最常见的就是程序的流程取决于你所使用的各种变量和属性的值,根据变量和属性的值确定后面运行的代码,有时会检...
    pro648阅读 1,607评论 2 27
  • 在iOS开发中,我们常常用到键值编码KVC和键值监听KVO两个东东,今天小编和大家分享的就是这两个东东在应用开发中...
    突然自我阅读 936评论 2 3