问题:KVC和KVO的keyPath一定是属性么?
作者:
姜小舟 | 来源:发表于
2020-05-11 15:06 被阅读0次
- KVC 支持实例变量,
- KVO 只能手动支持 实例变量。
即KVO需要自己在set方法里实现willChangeValueForKey didChangeValueForKey 还要自己实现 automaticallyNotifiesObserversForKey 手动进行监听。
-----------------------------------
//
// Student.h
//
#import <Foundation/Foundation.h>
@interface Student : NSObject {
NSString *_age;
}
- (void)setAge:(NSString *)age;
- (NSString *)age;
@property (nonatomic, strong) NSString *name;
@end
-----------------------------------
//
// Student.m
//
#import "Student.h"
@implementation Student
@synthesize name = _name;
- (void)setName:(NSString *)name {
_name = name;
}
- (NSString *)name {
return _name;
}
// 手动设定KVO
- (void)setAge:(NSString *)age {
[self willChangeValueForKey:@"age"];
_age = age;
[self didChangeValueForKey:@"age"];
}
- (NSString *)age {
return _age;
}
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
// 如果监测到键值为age,则指定为非自动监听对象
if ([key isEqualToString:@"age"]) {
return NO;
}
return [super automaticallyNotifiesObserversForKey:key];
}
@end
-----------------------------------
本文标题:问题:KVC和KVO的keyPath一定是属性么?
本文链接:https://www.haomeiwen.com/subject/dmxunhtx.html
网友评论