本文共 1889 字,大约阅读时间需要 6 分钟。
KVC 提供了一种通过字符串键值来间接修改对象属性的方式,适用于在不知道对象类型的情况下对属性进行操作。这种方法通过调用 valueForKey: 和 setValue:ForKey: 方法实现。
Student *stu = [[Student alloc] init];[stu setValue:@"John" forKey:@"name"];// 通过 key 取出当前值NSString *name = [stu valueForKey:@"name"];
[stu setValuesForKeysWithDictionary:@{ @"age": @20, @"name": @"Jim"}];// 批量赋值后获取所有值NSDictionary *values = [stu dictionaryWithValuesForKeys:@[@"name", @"age"]]; // 直接赋值stu.book.price = 20.0;// 通过 KVC 赋值[stu.book setValue:30.0 forKey:@"price"];// 通过 KVC 键路径赋值[stu setValue:40 forKeyPath:@"book.price"];
KVO 用于监听对象属性的变化,适用于需要追踪对象状态变化的场景。通过注册观察器,可以在属性值变化时执行相应的操作。
Teacher *teacher = [[Teacher alloc] init];
[stu addObserver:teacher forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"属性:%@,值:%@", keyPath, change);} Student *stu = [[Student alloc] init];[stu setValue:@"李斯" forKey:@"name"];NSLog(@"修改后的姓名:%@", stu.name);
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"keyPath: %@, object: %@, change: %@", keyPath, object, change);} @interface Book : NSObject@property (nonatomic, assign) double price;@end
@interface Student : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, retain) Book *book;@end
@interface Teacher : NSObject@end
int main(int argc, const char *argv) { @autoreleasepool { Student *stu = [[Student alloc] init]; [stu test]; } return 0;} 通过以上方法,开发者可以灵活地管理对象属性,并通过 KVO 实现属性值的监听功能。
转载地址:http://yfhfk.baihongyu.com/