Main.m
#import "Person.h"
#import "Dog.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//创建person对象
Person *person = [[Person alloc] init];
//1.使用KVC设置属性的值
[person setValue:@"zhangsan" forKey:@"name"]; //查找_name或者name
//如果属性是基本数据类型,得先包装成对象
[person setValue:@12 forKey:@"age"];
[person showInfo];
//2.通过KVC取得属性的值
NSString *name = [person valueForKey:@"name"];
NSLog(@"name:%@",name);
//如果属性类型为基本数据类型,则返回的值会自动被包装NSNumber
NSNumber *ageNum = [person valueForKey:@"age"];
NSLog(@"age:%@",ageNum);
/*
KVC设置值的时候,如果此属性有setter方法,则会优先调用setter方法,如果没有则直接设置值
KVC取值的时候,如果此属性有getter方法,则会优先调用getter方法,如果没有则直接取值
*/
Dog *dog = [[Dog alloc] init]; //dog:1
//使用KVC设置person的dog属性
//注意此处:dog设置给person的属性,计数值加一
[person setValue:dog forKey:@"dog"];
NSLog(@"dog:%ld",dog.retainCount);
[person release];
[dog release];
}
return 0;
}
Person.h
@class Dog;
@interface Person : NSObject {
@private
NSString *_name;
NSInteger _age;
Dog *_dog;
}
- (void)setName:(NSString *)name;
//打印个人信息
- (void)showInfo;
Person.m
#import "Dog.h"
@implementation Person
- (void)dealloc
{
NSLog(@"person dealloc");
[_dog release];
[_name release];
[super dealloc];
}
- (void)setName:(NSString *)name {
if (_name != name) {
[_name release];
_name = [name retain];
}
NSLog(@"调用了自己写的setter方法");
}
//打印个人信息
- (void)showInfo {
NSLog(@"name:%@ age:%ld",_name,_age);
}
Dog.h
@interface Dog : NSObject
Dog.m
- (void)dealloc
{
NSLog(@"dog dealloc");
[super dealloc];
}