KVC(key-value coding)鍵值編碼窗看,就是指iOS的開發(fā)中应役,可以允許開發(fā)者通過key名直接訪問對(duì)象的屬性诊胞,或者給對(duì)象的屬性賦值,而不需要調(diào)用明確的存取方法睦授。這樣可以在運(yùn)行時(shí)動(dòng)態(tài)訪問和修改對(duì)象的屬性.
KVC的定義都是通過NSKeyValueCoding 這個(gè)分類實(shí)現(xiàn)的
下面是這個(gè)分類的關(guān)鍵方法
- (nullable id)valueForKey:(NSString *)key; //直接通過Key來取值
- (void)setValue:(nullable id)value forKey:(NSString *)key; //通過Key來設(shè)值
- (nullable id)valueForKeyPath:(NSString *)keyPath; //通過KeyPath來取值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath; //通過KeyPath來設(shè)值
其他的一些方法
+ (BOOL)accessInstanceVariablesDirectly;
//默認(rèn)返回YES两芳,表示如果沒有找到Set<Key>方法的話,會(huì)按照_key去枷,_iskey怖辆,key,iskey的順序搜索成員删顶,設(shè)置成NO就不這樣搜索
- (BOOL)validateValue:(inout id __nullable * __nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
//KVC提供屬性值正確性驗(yàn)證的API竖螃,它可以用來檢查set的值是否正確、為不正確的值做一個(gè)替換值或者拒絕設(shè)置新值并返回錯(cuò)誤原因逗余。
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;
//這是集合操作的API特咆,里面還有一系列這樣的API,如果屬性是一個(gè)NSMutableArray录粱,那么可以用這個(gè)方法來返回腻格。
- (nullable id)valueForUndefinedKey:(NSString *)key;
//如果Key不存在,且沒有KVC無(wú)法搜索到任何和Key有關(guān)的字段或者屬性啥繁,則會(huì)調(diào)用這個(gè)方法菜职,默認(rèn)是拋出異常。
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;
//和上一個(gè)方法一樣旗闽,但這個(gè)方法是設(shè)值些楣。
- (void)setNilValueForKey:(NSString *)key;
//如果你在SetValue方法時(shí)面給Value傳nil,則會(huì)調(diào)用這個(gè)方法
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;
//輸入一組key,返回該組key對(duì)應(yīng)的Value宪睹,再轉(zhuǎn)成字典返回愁茁,用于將Model轉(zhuǎn)到字典。
KVC設(shè)值
- kvc優(yōu)先調(diào)用set屬性值方法亭病。即setter方法
- 如果沒有找到setter方法鹅很,會(huì)去檢查accessInstanceVariablesDirectly(默認(rèn)值為YES)有沒有返回YES,如果返回NO罪帖,KVC會(huì)執(zhí)行setValue:forUndefinedKey促煮。如果為YES,會(huì)去找_屬性值的成員變量
- 如果沒有setter方法整袁,也沒有_成員變量菠齿,會(huì)去搜索_is的成員變量,沒有的話會(huì)去找is的成員變量
*如果都沒有坐昙,會(huì)執(zhí)行setValue:forUndefinedKey绳匀。默認(rèn)是拋出異常
KVC取值
同設(shè)值,會(huì)先去檢查getter方法,如果沒有找到疾棵,會(huì)去檢查accessInstanceVariablesDirectly戈钢,然后按_,_is是尔,is的順序去搜索成員變量名殉了。
KVC處理集合
@avg,@count, @max, @min, @sum
#import <Foundation/Foundation.h>
@interface Book : NSObject
@property (nonatomic, copy) NSString* name;
@property (nonatomic, assign) CGFloat price;
@end
@implementation Book
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Book *book1 = [Book new];
book1.name = @"The Great Gastby";
book1.price = 10;
Book *book2 = [Book new];
book2.name = @"Time History";
book2.price = 20;
Book *book3 = [Book new];
book3.name = @"Wrong Hole";
book3.price = 30;
Book *book4 = [Book new];
book4.name = @"Wrong Hole";
book4.price = 40;
NSArray* arrBooks = @[book1,book2,book3,book4];
NSNumber* sum = [arrBooks valueForKeyPath:@"@sum.price"];
NSLog(@"sum:%f",sum.floatValue);
NSNumber* avg = [arrBooks valueForKeyPath:@"@avg.price"];
NSLog(@"avg:%f",avg.floatValue);
NSNumber* count = [arrBooks valueForKeyPath:@"@count"];
NSLog(@"count:%f",count.floatValue);
NSNumber* min = [arrBooks valueForKeyPath:@"@min.price"];
NSLog(@"min:%f",min.floatValue);
NSNumber* max = [arrBooks valueForKeyPath:@"@max.price"];
NSLog(@"max:%f",max.floatValue);
}
return 0;
}
打印結(jié)果:
2018-05-05 17:04:50.674243+0800 KVCKVO[35785:6351239] sum:100.000000
2018-05-05 17:04:50.675007+0800 KVCKVO[35785:6351239] avg:25.000000
2018-05-05 17:04:50.675081+0800 KVCKVO[35785:6351239] count:4.000000
2018-05-05 17:04:50.675146+0800 KVCKVO[35785:6351239] min:10.000000
2018-05-05 17:04:50.675204+0800 KVCKVO[35785:6351239] max:40.000000
@distinctUnionOfObjects 去重
@unionOfObjects 全集
兩者都是返回NSArray
KVC用法
- 動(dòng)態(tài)地取值和設(shè)值
- 用KVC來訪問和修改私有變量
- Model和字典轉(zhuǎn)換
- 修改一些控件的內(nèi)部屬性
- 操作集合
- 用KVC實(shí)現(xiàn)高階消息傳遞
KVO (key-value observing)使用
對(duì)目標(biāo)對(duì)象的某屬性添加觀察拟枚,當(dāng)該屬性發(fā)生變化時(shí)薪铜,通過觸發(fā)觀察者對(duì)象實(shí)現(xiàn)的KVO接口方法,來自動(dòng)的通知觀察者恩溅。
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
NSKeyValueObservingOptionNew:change字典包括改變后的值
NSKeyValueObservingOptionOld:change字典包括改變前的值
NSKeyValueObservingOptionInitial:注冊(cè)后立刻觸發(fā)KVO通知
NSKeyValueObservingOptionPrior:值改變前是否也要通知(這個(gè)key決定了是否在改變前改變后通知兩次)
處理變更通知
每當(dāng)監(jiān)聽的keyPath發(fā)生變化了隔箍,就會(huì)在這個(gè)方法中回調(diào)
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
如何實(shí)現(xiàn)我們的類不被KVO,需要關(guān)閉自動(dòng)生成KVO通知暴匠,然后手動(dòng)的調(diào)用
@interface Target : NSObject
{
int age;
}
// for manual KVO - age
- (int) age;
- (void) setAge:(int)theAge;
@end
@implementation Target
- (id) init
{
self = [super init];
if (nil != self)
{
age = 10;
}
return self;
}
// for manual KVO - age
- (int) age
{
return age;
}
- (void) setAge:(int)theAge
{
[self willChangeValueForKey:@"age"];
age = theAge;
[self didChangeValueForKey:@"age"];
}
+ (BOOL) automaticallyNotifiesObserversForKey:(NSString *)key {
if ([key isEqualToString:@"age"]) {
return NO;
}
return [super automaticallyNotifiesObserversForKey:key];
}
@end
手動(dòng)實(shí)現(xiàn)setter方法鞍恢,不進(jìn)行調(diào)用willChangeValueForKey:和didChangeValueForKey方法, automaticallyNotifiesObserversForKey 返回NO每窖,則可以禁用該類的kvo
KVO和線程
KVO行為是同步的帮掉,并且發(fā)生與所觀察的值發(fā)生變化的同樣的線程上。及setter所在的線程
Son *s = [Son new];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"current thread: %@",[NSThread currentThread]);
[s addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
dispatch_async(dispatch_get_main_queue(), ^{
s.age = 10;
});
});
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"current thread: %@",[NSThread currentThread]);
}
輸出
2023-04-20 16:50:57.840429+0800 testUI[43718:25110937] current thread: <NSThread: 0x6000033e7800>{number = 6, name = (null)}
2023-04-20 16:50:57.855796+0800 testUI[43718:25110670] current thread: <_NSMainThread: 0x6000033a40c0>{number = 1, name = main}
KVO實(shí)現(xiàn)
KVO是通過isa-swizzling實(shí)現(xiàn)的窒典,即編譯器會(huì)被觀察對(duì)象創(chuàng)造一個(gè)派生類蟆炊,并將所有被觀察對(duì)象的isa指向這個(gè)派生類。如果用戶觀察了這個(gè)目標(biāo)類的一個(gè)屬性瀑志,那么派生類會(huì)重寫這個(gè)屬性的setter方法涩搓,并在其中添加進(jìn)行通知的代碼。OC在發(fā)消息時(shí)劈猪,會(huì)通過isa指針找打?qū)ο笏鶎俚念悓?duì)象(即派生類)昧甘,所以setter方法其實(shí)是調(diào)用的派生類的。