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