问题:什么是KVC/KVO

2020-05-11  本文已影响0人  姜小舟

NSKeyValueCoding,一个非正式的 Protocol,提供一种机制来间接访问对象的属性,并不需要调用setter/getter函数或者类的实例变量。

-----------------------------------------
#ClassB.h文件 不声明暴露属性
@interface ClassB : NSObject
@end
-----------------------------------------
#ClassB.m文件 声明属性
#import "ClassB.h"

@interface ClassB()
@property (nonatomic,assign) NSInteger age;
@end

@implementation ClassB
@end
-----------------------------------------
-----------------------------------------
#ClassC.h文件 不声明暴露属性你
@interface ClassC : NSObject
@end
-----------------------------------------
#ClassC.m文件 声明属性
#import "ClassC.h"
#import "ClassB.h"

@interface ClassC()
@property (nonatomic,copy) NSString *str;
@property (nonatomic,assign) NSInteger num;
@property (nonatomic, strong) NSArray * array;
@property (nonatomic, strong) ClassB * b;
@end

@implementation ClassC
@end
-----------------------------------------

理论上来说,外部是访问不到ClassC.m的3个私有变量的,但KVC的强大之处就显示出来了,具体应用如下:

ClassC *a = [[ClassC alloc] init];

//KVC之set
[a setValue:@"HelloWorld" forKey:@"str"];
[a setValue:@2015 forKey:@"num"];
[a setValue:@[@"HearthStone", @2] forKey:@"array"];
[a setValue:@23 forKeyPath:@"b.age"];

//KVC之get
NSString *str = [a valueForKey:@"str"];
NSInteger value = [[a valueForKey:@"value"] integerValue];  //id 转为 NSInteger
NSArray *array = [a valueForKey:@"array"];
NSInteger age = [[a valueForKey:@"b.age"] integerValue];  //id 转为 NSInteger

NSLog(@"\n%@\n%ld\n%@\n%ld", str, (long)value, array, age);
/*打印结果:
HelloWorld
2015
(
HearthStone,
2
)
23
*/

NSKeyValueObserving,一个非正式的Protocol,提供一种机制来间接观察其他对象属性的变化。

#添加观察对象 
[_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
 
#实现监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentOffset"])
    {
        NSLog(@"%@", change);
    }
}

#移除监听对象
- (void)dealloc {
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
}
上一篇 下一篇

猜你喜欢

热点阅读