IOS开发之kvc简单介绍

1.概念:
kvc也就是key value coding 就是键值编码。我们利用kvc可以给对象初始化,也可以去某个对象的值赋给另一个对象。
2.简单例子(利用kvc初始化对象,取某个对象的值付给另一对象)

person类:

#import 
#import "Book.h"
@interface Person : NSObject
@property (nonatomic,copy) NSString* name;
@property (nonatomic,assign) int age;
@property (nonatomic,strong) Book *book;
@end

Book类:

#import 
@interface Book : NSObject
@property (nonatomic,copy) NSString *bookName;
@end
//
//  main.m
//  KVCDemo_01
//
//  Created by QiZhang on 8/5/15.
//  Copyright (c) 2015 QiZhang. All rights reserved.
//

#import 
#import "Person.h"
int main(int argc, const char * argv[]) {
    // 1.利用kvc可以为对象初始化
    Person *p1 = [[Person alloc] init];
    [p1 setValue:@"SanZhang" forKeyPath:@"name"];
    [p1 setValue:@"23" forKeyPath:@"age"];
    Book *b1 = [[Book alloc] init];
    b1.bookName = @"Iphone";
    p1.book = b1;


    Person *p2 = [[Person alloc] init];
    [p2 setValue:@"SiLi" forKeyPath:@"name"];
    [p2 setValue:@"20" forKeyPath:@"age"];
    Book *b2 = [[Book alloc] init];
    [b2 setValue:@"IOS" forKeyPath:@"bookName"];
    [p2 setValue:b2 forKeyPath:@"book"];

    NSLog(@"%@-----%@",p1,[p2 valueForKey:@"name"]);


    NSLog(@"*******************");
    NSArray *persons = @[p1,p2];
    NSMutableArray *arrayM = [NSMutableArray array];
    [arrayM addObject:[persons valueForKeyPath:@"book.bookName"]]; //利用kvc可以很方便的去取值
    NSLog(@"%@",arrayM);
    return 0;
}

运行结果:

2015-08-05 19:18:42.154 KVCDemo_01[13536:567138] <Person:0x100211e80>,{name:SanZhang,age:23}-----SiLi
2015-08-05 19:18:42.155 KVCDemo_01[13536:567138] *******************
2015-08-05 19:18:42.155 KVCDemo_01[13536:567138] (
        (
        Iphone,
        IOS
    )
)

你可能感兴趣的:(IOS学习笔记,ios开发,ios)