iOS学习记录

Objective-C Runtime 学习笔记之分类添加关联对

2016-06-06  本文已影响72人  我系哆啦

关联对象(Associated Object)

关联对象最佳实践

关联对象理解起来不难,实际使用也很容易,但是不能滥用,以下是一个实际使用的例子。

<pre>
@interface People : NSObject
{
NSString * _name;
NSString * _reName;
}

@property (nonatomic,assign) NSInteger age;
@property (nonatomic,strong) NSString *country;

/**

@end
</pre>

<pre>
@interface People (BTExtend)
//在分类里直接添加属性的话,并不会生成成员变量和set以及get方法
@property (nonatomic, copy) NSString *company;
@property (nonatomic, strong) NSString *position;
@end

@implementation People (BTExtend)

<pre>
void ivarAndPropertyList()
{
People *people = [[People alloc] initWithName:@"大傻" reName:@"二傻"];
people.age = 18;
people.country = @"japan";
people.company = @"tv";
people.position = @"av";

NSDictionary *ivarList = [people allIvar];
NSDictionary *propertyList = [people allProperty];

NSLog(@"ivarList:%@\npropertyList:%@",ivarList,propertyList);

}

//运行结果
2016-06-06 22:22:49.271 runtimeDemo[1368:49233] ivarList:{
** "_age" = 18;**
** "_country" = japan;**
** "_name" = "\U5927\U50bb";**
** "_reName" = "\U4e8c\U50bb";**
}
propertyList:{
** age = 18;**
** company = tv;**
** country = japan;**
** position = av;**
}
</pre>

上一篇 下一篇

猜你喜欢

热点阅读