属性
- 在类中声明一个属性会生成成员变量并声明和实现对应的set,get方法
- 在分类中声明一个属性只会声明对应的set,get方法
- 不能直接在分类中添加成员变量,但可以通过字典间接实现,涉及线程安全,不推荐这种方式
#import "Person.h"
@interface Person (Eat)
@property (assign, nonatomic) int age;
@end
#import "Person+Eat.h"
@implementation Person (Eat)
NSMutableDictionary* ages_;
+ (void)load{
ages_ = [NSMutableDictionary dictionaryWithCapacity:1];
}
- (void)setAge:(int)age{
NSString* key = [NSString stringWithFormat:@"%p",self];
ages_[key] = @(age);
}
- (int)age{
NSString* key = [NSString stringWithFormat:@"%p",self];
return [ages_[key] intValue];
}
@end
关联对象
- key可以用宏定义字符串代替
#import "Person+Eat.h"
#import <objc/runtime.h>
@implementation Person (Eat)
static const void * ageKey = &ageKey;
- (void)setAge:(int)age{
objc_setAssociatedObject(self, ageKey, @(age), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (int)age{
return [objc_getAssociatedObject(self, ageKey) intValue];
}
@end
-
关联对象原理
(1)关联对象不是存储在被关联对象本身内存中
(2)关联对象存储在全局统一的一个AssociationsManager中的AssociationsHashMap
image.png
网友评论