Person.h
日志:
#import <Foundation/Foundation.h>
#import "Father.h"
#import "Book.h"
@interface Person : NSObject {
@public
NSString *_fullName;
@private
NSString *_name;
Father *_father;
NSArray *_books;
}
@end
Father.h
@interface Father : NSObject {
@protected
NSString *_name;
}
@end
Book.h
#import <Foundation/Foundation.h>
@interface Book : NSObject {
@private
NSString *_name;
float _price;
}
@end
使用代码:
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person *person = [[Person alloc] init];
//直接访问public变量
person->_fullName = @"ALI TOM";
NSLog(@"_fullName :%@",person->_fullName);
//KVC方式
[person setValue:@"TOM" forKey:@"_name"];
NSLog(@"_name :%@", [person valueForKey:@"_name"]);
Father *father = [[Father alloc] init];
[father setValue:@"JACK" forKey:@"_name"];
[person setValue:father forKey:@"_father"];
//KVC路径访问
NSLog(@"father.name :%@", [person valueForKeyPath:@"_father._name"]);
[person setValue:@"JERRY" forKeyPath:@"_father._name"];
NSLog(@"father.name :%@", [person valueForKeyPath:@"_father._name"]);
NSMutableArray *bookArray = [NSMutableArray arrayWithCapacity:3];
for (int i=0; i<3; i++) {
Book *book = [[Book alloc] init];
NSString *bookName = [NSString stringWithFormat:@"book%d", i];
[book setValue:bookName forKey:@"_name"];
[book setValue:@((i + 1) * 10.2) forKey:@"_price"];
[bookArray addObject:book];
[book release];
}
[person setValue:bookArray forKey:@"_books"];
//获取所有的数
NSArray *array = [person valueForKeyPath:@"_books._name"];
NSLog(@"%@", array);
//KVC计算
//通过@count获取集合book个数
NSNumber *bookCount = [person valueForKeyPath:@"_books.@count"];
NSLog(@"book count :%@", bookCount);
//价格总和
NSNumber *sum = [person valueForKeyPath:@"_books.@sum._price"];
NSLog(@"sum :%@", sum);
//价格平均值
NSNumber *avg = [person valueForKeyPath:@"_books.@avg._price"];
NSLog(@"vag :%@", avg);
//最低价格
NSNumber *min = [person valueForKeyPath:@"_books.@min._price"];
NSLog(@"min :%@", min);
//最高价格
NSNumber *max = [person valueForKeyPath:@"_books.@max._price"];
NSLog(@"max :%@", max);
}
return 0;
}
日志:
2013-03-17 13:19:13.835 PersonKVCDemo[1388:303] _fullName :ALI TOM
2013-03-17 13:19:13.837 PersonKVCDemo[1388:303] _name :TOM
2013-03-17 13:19:13.838 PersonKVCDemo[1388:303] father.name :JACK
2013-03-17 13:19:13.839 PersonKVCDemo[1388:303] father.name :JERRY
2013-03-17 13:19:13.840 PersonKVCDemo[1388:303] (
book0,
book1,
book2
)
2013-03-17 13:19:13.840 PersonKVCDemo[1388:303] book count :3
2013-03-17 13:19:13.841 PersonKVCDemo[1388:303] sum :61.2
2013-03-17 13:19:13.842 PersonKVCDemo[1388:303] vag :20.4
2013-03-17 13:19:13.843 PersonKVCDemo[1388:303] min :10.2
2013-03-17 13:19:13.843 PersonKVCDemo[1388:303] max :30.6