KVC和KVO

KVC和KVO
今天在這里給大家詳解一下KVC和KVO的用法, 在這里首先給大家介紹一下KVC的用法,雖然他倆看似只差一個字母但,但其實兩種放法的機制相差很大,千萬不要被表象所蒙騙哦, 下面分別介紹了兩種機制的使用方式, 理解之后你就明白, 他倆一毛錢關(guān)系也沒有哦 ^- -^
KVC
KVC(鍵值編碼,是KeyValue Coding的簡稱),它是一種可以直接通過字符串的名字(key)來訪問類屬性的機制.使用該機制不需要調(diào)取實例變量就可以訪問對象屬性,并對屬性進行賦值.在iOS開發(fā)中, KVC經(jīng)常會被使用,在給Model類進行賦值時,你會經(jīng)常用到KVC, 如果你還不知道Model,請自行補習(xí).下面的實例清單會涉及Model類.

實例清單1.1 KVC的最基礎(chǔ)用法(setValue:forKey:):

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

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文件內(nèi)容/此.m文件無內(nèi)容(在真正的開發(fā)中.m中是有內(nèi)容, 在這里為了減少我的工作量,我lazy一下)

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic, strong) NSString *address;
@end
// VC中的.m文件中內(nèi)容
// 定義一個字典, 在這里請注意,字典中Key值要和Model類中屬性名一致,不然會出現(xiàn)問題,把出錯的話,就復(fù)制粘貼吧! (^-#-^)
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];
    
    //關(guān)鍵路徑賦值
    [per setValue:@"male" forKeyPath:@"stu.sex"];
    Student *stu = [[Student alloc] init];
    NSLog(@"%@", stu);
}

KVO
重點來了,KVO的時間到了,KVO的全稱叫(Key-value observing),在我理解看來,就是一種監(jiān)聽機制,能夠?qū)崟r的監(jiān)聽關(guān)鍵Key值得變化,現(xiàn)在你可能不明白這個Key到底是神魔玩意, 先不要著急,繼續(xù)讀下去,在這我先舉幾個例子,比如:UIscrollView中屬性contentOffset, 自定義的BOOL屬性, UIView及子類的backgroundColor屬性等等都可以作為Key,即觀察的對象.廢話不多說了,實例才能證明一切.
聲明:如果想實現(xiàn)下列清單中的案例請粘貼到工程中就可以了,具體的實現(xiàn)可能使你更加的了解KVO -%-

實例清單如下:

//自定義的TitleView(網(wǎng)易新聞的文字橫條)

//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];
    }
}
// 當(dāng)然自定義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 = @[@"頭條", @"熱點", @"財經(jīng)", @"新聞", @"汽車"];  
    [self.view addSubview:self.viewOfTitle]; 
}

// KOV的實現(xiàn),事件處理都在這里進行處理, 這是重點哦, 好好理解一下吧
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {

//objectForKey:@"new" 中的只能寫@"new"(新的值, 監(jiān)聽的Key的變化的值) 或者寫 @"old"(舊的值, 監(jiān)聽Key變化之前的值)
// 在這里我們獲取新值(變化后的值)
    CGFloat x = [[change objectForKey:@"new"] CGPointValue].x / 5.0f;
    self.viewOfRedline.frame = CGRectMake(x, 64, CGRectGetWidth(self.view.bounds) / 5, 2); 
}

// UIScrollView的協(xié)議方法之一
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 5;
}

// UIScrollView的協(xié)議方法之一
- (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;
}

 // 改變標(biāo)題的顏色
- (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];    
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扩然,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子枚驻,更是在濱河造成了極大的恐慌待诅,老刑警劉巖碴倾,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件池磁,死亡現(xiàn)場離奇詭異跪解,居然都是意外死亡炉旷,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門叉讥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來窘行,“玉大人,你說我怎么就攤上這事图仓」蘅” “怎么了?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵救崔,是天一觀的道長惶看。 經(jīng)常有香客問我,道長六孵,這世上最難降的妖魔是什么纬黎? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮劫窒,結(jié)果婚禮上本今,老公的妹妹穿的比我還像新娘。我一直安慰自己主巍,他們只是感情好冠息,可當(dāng)我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著煤禽,像睡著了一般铐达。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上檬果,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天瓮孙,我揣著相機與錄音唐断,去河邊找鬼。 笑死杭抠,一個胖子當(dāng)著我的面吹牛脸甘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播偏灿,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼丹诀,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了翁垂?” 一聲冷哼從身側(cè)響起铆遭,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎沿猜,沒想到半個月后枚荣,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡啼肩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年橄妆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片祈坠。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡害碾,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出赦拘,到底是詐尸還是另有隱情慌随,我是刑警寧澤,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布躺同,位于F島的核電站儒陨,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏笋籽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一椭员、第九天 我趴在偏房一處隱蔽的房頂上張望车海。 院中可真熱鬧,春花似錦隘击、人聲如沸侍芝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽州叠。三九已至,卻和暖如春凶赁,著一層夾襖步出監(jiān)牢的瞬間咧栗,已是汗流浹背逆甜。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留致板,地道東北人交煞。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像斟或,于是被迫代替她去往敵國和親素征。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 概念 先來看看概念萝挤,Key-value coding (KVC) 和 key-value observing (K...
    wuwy閱讀 1,313評論 0 1
  • 目錄:1.KVC用法御毅;2.KVC和對象的setter、getter方法的區(qū)別怜珍;3.key和keyPath的區(qū)別端蛆;4...
    倫倫子_f7b3閱讀 574評論 0 1
  • 什么是KVC和KVO欺税?兩者之間有何關(guān)系 KVC : 鍵值編碼,是Key Value Coding 的簡稱揭璃,coco...
    蘭章海晏閱讀 3,542評論 0 3
  • 在編程中晚凿,最常見的就是程序的流程取決于你所使用的各種變量和屬性的值,根據(jù)變量和屬性的值確定后面運行的代碼瘦馍,有時會檢...
    pro648閱讀 1,642評論 2 27
  • 在iOS開發(fā)中情组,我們常常用到鍵值編碼KVC和鍵值監(jiān)聽KVO兩個東東燥筷,今天小編和大家分享的就是這兩個東東在應(yīng)用開發(fā)中...
    突然自我閱讀 994評論 2 3