标签:ini ios sar ack ace 属性 bsp gnu nsstring
@implementation Person
{
@private
double _height;
}
- (void)printHeight
{
NSLog(@"height是%f", _height);
}
Person.h中:
- (void)printHeight;
看我们如何修改这个height的值:
void test()
{
Person *p = [[Person alloc] init];
[p setValue:@10.5 forKey:@"height"];
[p printHeight];
就这样就能更改了这个height的值。
forKeyPath中可以利用.运算符, 就可以一层一层往下查找对象的属性
当然 在一般的修改一个对象的属性的时候,forKey和forKeyPath,没什么区别。如:
[p setValue:@"jack" forKey:@"name"];
[p setValue:@"jack" forKeyPath:@"_name"];
一样能修改这个name和age的值。
@class Bone;
@interface Dog : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Bone *bone;
这个是bone的属性:
@interface Bone : NSObject
@property (nonatomic, strong) NSString *type;
我们先初始化这些对象:
Person *p = [[Person alloc] init];
p.dog = [[Dog alloc] init];
然后接下来我们给这个bone赋值:
p.dog.bone.type = @"狗骨";
[p setValue:@"猪骨" forKeyPath:@"dog.bone.type"];
[p.dog setValue:@"猪骨" forKeyPath:@"bone.type"];
void test()
{
Person *p = [[Person alloc] init];
p.dog = [[Dog alloc] init];
p.dog.bone = [[Bone alloc] init];
比如person有很多书:
Person *p = [[Person alloc] init];
Book *book1 = [[Book alloc] init];
book1.name = @"ios之Ui布局";
book1.price = 10.5;
Book *book2 = [[Book alloc] init];
book2.name = @"ios之OC基础";
book2.price = 18.5;
Book *book3 = [[Book alloc] init];
book3.name = @"ios之多线程";
book3.price = 20.5;
Book *book4 = [[Book alloc] init];
book4.name = @"ios之内存管理";
book4.price = 10.5;
然后我们取出books数组中每一个元素的name属性值,放到一个新的数组中返回
NSArray *names = [p valueForKeyPath:@"books.name"];
这样就能办到。
还有一个比较牛逼的 是取得一些特殊的值,如:avg、sum
NSNumber *avgNumber = [p valueForKeyPath:@"books.@avg.price"];
标签:ini ios sar ack ace 属性 bsp gnu nsstring
原文地址:http://www.cnblogs.com/xsyl/p/6085913.html