一、KVC设值的原理
二、KVC取值原理
----------------------------MJPerson.h--------------------------
#import <Foundation/Foundation.h>
@interface MJPerson : NSObject
{
@public
// int age;
// int isAge;
// int _isAge;
// int _age;
}
@end
-------------------------------MJPerson.m-------------------------------
#import "MJPerson.h"
@implementation MJPerson
//- (int)getAge
//{
// return 11;
//}
//- (int)age
//{
// return 12;
//}
//- (int)isAge
//{
// return 13;
//}
//- (int)_age
//{
// return 14;
//}
//- (void)setAge:(int)age
//{
// NSLog(@"setAge: - %d", age);
//}
//- (void)_setAge:(int)age
//{
// NSLog(@"_setAge: - %d", age);
//}
//- (void)willChangeValueForKey:(NSString *)key
//{
// [super willChangeValueForKey:key];
// NSLog(@"willChangeValueForKey - %@", key);
//}
//
//- (void)didChangeValueForKey:(NSString *)key
//{
// NSLog(@"didChangeValueForKey - begin - %@", key);
// [super didChangeValueForKey:key];
// NSLog(@"didChangeValueForKey - end - %@", key);
//}
// 默认的返回值就是YES
//+ (BOOL)accessInstanceVariablesDirectly
//{
// return YES;
//}
@end
------------------------------MJObserver.h-----------------------------
#import <Foundation/Foundation.h>
@interface MJObserver : NSObject
@end
------------------------------MJObserver.m------------------------------
#import "MJObserver.h"
@implementation MJObserver
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"observeValueForKeyPath - %@", change);
}
@end
#import <Foundation/Foundation.h>
#import "MJPerson.h"
#import "MJObserver.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
MJPerson *person = [[MJPerson alloc] init];
// person->_age = 10;
// person->_isAge = 11;
// person->age = 12;
// person->isAge = 13;
NSLog(@"%@", [person valueForKey:@"age"]);
}
return 0;
}
void test()
{
MJObserver *observer = [[MJObserver alloc] init];
MJPerson *person = [[MJPerson alloc] init];
// 添加KVO监听
[person addObserver:observer forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
// 通过KVC修改age属性
[person setValue:@10 forKey:@"age"];
// [person willChangeValueForKey:@"age"];
// person->_age = 10;
// [person didChangeValueForKey:@"age"];
// 移除KVO监听
[person removeObserver:observer forKeyPath:@"age"];
}
网友评论