KVC赋值的顺序
验证
#import <Foundation/Foundation.h>
@interface MZPerson : NSObject
{
@public
int age;
int isAge;
int _isAge;
int _age;
}
@end
@implementation MZPerson
//- (void)setAge:(int)age {
// NSLog(@"setAge: - %d", age);
//}
//
//- (void)_setAge:(int)age {
// NSLog(@"_setAge: - %d", age);
//}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
MZPerson *person = [[MZPerson alloc] init];
[person setValue:@12 forKey:@"age"];
NSLog(@"世界一盘棋, ZM大博弈.");
}
return 0;
}
在注释掉两个set方法,验证成员属性赋值的时候,可以通过断点来验证,如下图所示。
需要特别注意的是:KVC的赋值会出发KVO,可能的原因是,KVO生成了一个子类,并且在赋值前后分别调用了 willChangeValueForKey:
和 didChangeValueForKey:
。
- (void)setName:(NSString *)name {
[self willChangeValueForKey:name];
[super setName:name];
[self didChangeValueForKey:name];
}
//或
[self willChangeValueForKey:_name];
_name = newValue;
[self didChangeValueForKey:_name];
KVC的取值顺序
验证
#import <Foundation/Foundation.h>
@interface MZPerson : NSObject
{
@public
// int _age;
int _isAge;
int age;
int isAge;
}
@end
@implementation MZPerson
- (instancetype)init {
if (self = [super init]) {
// _age = 1;
_isAge = 2;
age = 3;
isAge = 4;
}
return self;
}
//- (int)getAge {
// return 11;
//}
//- (int)age {
// return 12;
//}
//- (int)isAge {
// return 13;
//}
//- (int)_age {
// return 14;
//}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
MZPerson *person = [[MZPerson alloc] init];
int intValue = [[person valueForKey:@"age"] intValue];
NSLog(@"%d", intValue);
}
return 0;
}