kvc

//
//  main.m
//  kvcdemo01
//
//  Created by ganchaobo on 13-5-6.
//  Copyright (c) 2013年 ganchaobo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "student.h"
#import "book.h"
//直接访问
void kvc1(){
    student * stu=[[[student alloc] init] autorelease];
    //间接访问
    //先找getname方法,key _key
    [stu setValue:@"zs" forKey:@"name"];
    NSLog(@"%@",stu.name);
    NSLog(@"%@",[stu valueForKey:@"name"]);
}
//直接访问,根据对象先找对象中setprice方法,如果找不到price,_price
void kvc2(){
    student * stu=[[[student alloc] init] autorelease];
    stu.bk=[[[book alloc] init] autorelease];
    [stu.bk setValue:@1.5 forKey:@"price"];
    NSLog(@"%f",[stu.bk price]);
    NSLog(@"%f",[[stu.bk valueForKey:@"price"] floatValue]);
}

//设置多个key
void kvc3(){
    student *stu=[[[student alloc] init] autorelease];
    NSDictionary *dic=@{@"name":@"zs",@"age":@12};
    [stu setValuesForKeysWithDictionary:dic];//设置多个key的值
    NSDictionary *dic1=[stu dictionaryWithValuesForKeys:@[@"name",@"age"]];
    NSLog(@"%@",dic1);
}
//keypath间接访问
void kvc4(){
    student *stu=[[[student alloc]init]autorelease];
    stu.bk=[[[book alloc] init] autorelease];
    //间接设置值
    [stu setValue:@15 forKeyPath:@"bk.price"];
    NSLog(@"%f",stu.bk.price);
    NSLog(@"%f",[[stu valueForKeyPath:@"bk.price"]floatValue]);
}

void kvc5(){
    student *stu=[[[student alloc]init]autorelease];
    stu.name=@"mike";
    student *stu1=[[[student alloc]init]autorelease];
    stu1.name=@"jack";
    student *stu2=[[[student alloc]init]autorelease];
    stu2.name=@"jim";
    NSArray *arr=@[stu,stu1,stu2];
    NSArray *arr1=[arr valueForKeyPath:@"name"];
    NSLog(@"%@",arr1);
    
}

void kvc6(){
    
    student *stu=[[[student alloc]init]autorelease];
    stu.bk=[book bookwithprice:1.5];
    
    
    student *stu1=[[[student alloc]init]autorelease];
    stu1.bk=[book bookwithprice:1.6];
    
    student *stu2=[[[student alloc]init]autorelease];
    stu2.bk=[book bookwithprice:1.7];
    NSArray *arr=@[stu1,stu2,stu];
    NSArray *arr1= [arr valueForKeyPath:@"bk.price"];
    NSLog(@"%@",arr1);

    
}


void kvc7(){
    
    student *stu=[[[student alloc]init]autorelease];
    
    book *book1=[book bookwithprice:1.5];
    book *book2=[book bookwithprice:1.6];
    book *book3=[book bookwithprice:1.7];
    stu.books=@[book1,book2,book3];
   NSArray *arr= [stu.books valueForKeyPath:@"price"];
    NSLog(@"%@",arr);
    NSLog(@"%f",[[stu.books valueForKeyPath:@"@sum.price"]floatValue]);
    
    
    NSLog(@"%i",[[stu.books valueForKeyPath:@"@count"] intValue]);
}


int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        kvc7();
        
    }
    return 0;
}














www.shudanyu.com
原文地址:https://www.cnblogs.com/gcb999/p/3063857.html