IOS OC KVC

KVC的打印与包装

main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Book.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        Person *p = [[Person alloc] init];
        [p setValue:@"jake" forKeyPath:@"name"];
        [p setValue:@"80" forKeyPath:@"age"];
        Book *b = [[Book alloc] init];
        b.bookName = @"ios";
        p.book = b;

        Person *p1 = [[Person alloc] init];
        [p1 setValue:@"mike" forKeyPath:@"name"];
        [p1 setValue:@"18" forKeyPath:@"age"];
        Book *b1 = [[Book alloc] init];
        b1.bookName = @"iPhone";
        p1.book = b1;

        NSArray *persons = @[p, p1];
        NSLog(@"%@", persons);
        
        NSArray *array = [persons valueForKeyPath:@"book.bookName"];
        NSLog(@"%@", array);
    }
    return 0;
}

void demo1()
{
    Person *p = [[Person alloc] init];
    // 使用KVC间接修改对象属性时,系统会自动判断对象属性的类型,并完成转换
    [p setValue:@"jake" forKeyPath:@"name"];
    // NSNumber 基本数据类型
    // NSValue 结构体
    [p setValue:@"80" forKeyPath:@"age"];
    
    Person *p1 = [[Person alloc] init];
    // 使用KVC间接修改对象属性时,系统会自动判断对象属性的类型,并完成转换
    [p1 setValue:@"mike" forKeyPath:@"name"];
    // NSNumber 基本数据类型
    // NSValue 结构体
    [p1 setValue:@"18" forKeyPath:@"age"];
    
    NSLog(@"%@ %@", p, [p1 valueForKeyPath:@"name"]);
    
    NSArray *persons = @[p, p1];
    NSLog(@"%@", persons);
    
    // 只生成name的数组
    //        NSMutableArray *arrayM = [NSMutableArray array];
    //        for (Person *p in persons) {
    //            [arrayM addObject:p.name];
    //        }
    //
    //        NSLog(@"%@", arrayM);
    // KVC按照键值路径取值时,如果对象不包含指定的键值,会自动进入对象内部,查找对象属性
    NSArray *array = [persons valueForKeyPath:@"name"];
    NSLog(@"%@", array);
}

Person.h
#import <Foundation/Foundation.h>
@class Book;

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

Person.m

#import "Person.h"

@implementation Person

//	重写打印方法
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p> {name: %@, age: %d book: %@}", self.class, self, self.name, self.age, self.book];
}

@end

Book.h
#import <Foundation/Foundation.h>

@interface Book : NSObject
@property (nonatomic, copy) NSString *bookName;
@end

Book.m

#import "Book.h"

@implementation Book

- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p> {bookName: %@}", [self class], self, self.bookName];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值