首页 > 学院 > 开发设计 > 正文

IOS开发之KVC与KVO简述

2019-11-14 19:30:57
字体:
来源:转载
供稿:网友

KVC:Key-Value Coding

KVO:Key-Value Observing

 

Person.m

#import <Foundation/Foundation.h>@interface Person : NSObject{    //该访问修饰符用于说明即使私有成员变量也可以通过kvc方式访问和赋值    @PRivate    NSString *_name;    NSArray *_dogs;}@end@implementation Person@end

Dog.m

#import <Foundation/Foundation.h>@class Person;@interface Dog : NSObject{    @private    NSInteger _age;    Person *_owner;}@end@implementation Dog@end

PersonObserve.m

#import <Foundation/Foundation.h>#import "Person.h"@interface PersonObserve : NSObject@end@implementation PersonObserve- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    Person *p = (Person *)object;    //使用kvc方式获取成员变量keypath的值    NSLog(@"%@",[p valueForKey:keyPath]);}@end

main.m

#import <Foundation/Foundation.h>#import "Person.h"#import "PersonObserve.h"#import "Dog.h"int main(int argc, const char * argv[]) {    //观察者类    PersonObserve *po = [[PersonObserve alloc] init];    Person *p = [[Person alloc] init];    //使用kvo方式对成员变量“name”的属性值变化增加观察者po    //po将在该属性值发生变化时执行- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context方法    [p addObserver:po forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];        //通过kvc方式设置成员变量“name”的属性值    //出发观察者执行对应方法    [p setValue:@"zhangsan" forKey:@"name"];            //kvc中forKeyPath的用法    Dog *d = [[Dog alloc] init];    [d setValue:p forKey:@"owner"];    [d setValue:@"lisi" forKeyPath:@"owner.name"];        //移除对私有成员变量“name”的观察    [p removeObserver:po forKeyPath:@"name"];            Dog *d1 = [[Dog alloc] init];    [d1 setValue:@10 forKey:@"age"];    Dog *d2 = [[Dog alloc] init];    [d2 setValue:@20 forKey:@"age"];            NSArray *array = [NSArray arrayWithObjects:d1,d2, nil];    [p setValue:array forKey:@"dogs"];            //kvc中valueForKeyPath数组内置表达式的用法    NSLog(@"dogs.age = %@",[p valueForKeyPath:@"dogs.age"]);    NSLog(@"dogs.age.sum = %@",[p valueForKeyPath:@"dogs.@sum.age"]);//dogs数组中age的总和    NSLog(@"dogs.age.avg = %@",[p valueForKeyPath:@"dogs.@avg.age"]);//dogs数组中age的平均值    NSLog(@"dogs.age.max = %@",[p valueForKeyPath:@"dogs.@max.age"]);//dogs数组中age的最大值    NSLog(@"dogs.age.min = %@",[p valueForKeyPath:@"dogs.@min.age"]);//dogs数组中age的最小值            return 0;}

结果:

2015-03-07 21:09:34.611 KVC&KOC[3079:122638] zhangsan2015-03-07 21:09:34.612 KVC&KOC[3079:122638] lisi2015-03-07 21:09:34.613 KVC&KOC[3079:122638] dogs.age = (    10,    20)2015-03-07 21:09:34.613 KVC&KOC[3079:122638] dogs.age.sum = 302015-03-07 21:09:34.613 KVC&KOC[3079:122638] dogs.age.avg = 152015-03-07 21:09:34.613 KVC&KOC[3079:122638] dogs.age.max = 202015-03-07 21:09:34.613 KVC&KOC[3079:122638] dogs.age.min = 10Program ended with exit code: 0

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表