```
static int height_;
-(void)setHeight:(int)height
{
height_ = height;
}
- (int)height
{
return height_;
}
```
height_
静态全局变量与类并没有关联,无论对象创建与销毁,只要程序在运行height_
变量就存在,并不是真正意义上的属性。NSObject *obj1 = [[NSObject alloc] init]; obj1.height = 10; NSLog(@"obj1:%i",obj1.height); // 打印结果10 NSObject *obj2 = [[NSObject alloc] init]; obj2.height = 120; NSLog(@"obj1:%i",obj1.height); // 打印结果120 NSLog(@"obj2:%i",obj2.height); // 打印结果120
NSMutableDictionary *dictionary_;
+ (void)load
{
dictionary_ = [NSMutableDictionary dictionary];
}
-(void)setHeight:(int)height
{
// 对象的指针地址作为Key,保证唯一
NSString *key = [NSString stringWithFormat:@"%p",self];
dictionary_[key] = @(height);
}
- (int)height
{
NSString *key = [NSString stringWithFormat:@"%p",self];
return [dictionary_[key] intValue];
}
dictionary_
静态全局变量与类并没有关联,无论对象创建与销毁,只要程序在运行dictionary_
变量就存在,并不是真正意义上的属性。```
-(void)setHeight:(int)height
{
objc_setAssociatedObject(self, @selector(height), @(height), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (int)height
{ _cmd = @selector(height);
return [objc_getAssociatedObject(self, @selector(height)) intValue];
}
```
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) { OBJC_ASSOCIATION_ASSIGN = 0, // 指定一个弱引用相关联的对象 OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, // 指定相关对象的强引用,非原子性 OBJC_ASSOCIATION_COPY_NONATOMIC = 3, // 指定相关的对象被复制,非原子性 OBJC_ASSOCIATION_RETAIN = 01401, // 指定相关对象的强引用,原子性 OBJC_ASSOCIATION_COPY = 01403 // 指定相关的对象被复制,原子性 };
- (void)removeAssociatedObjects { // 移除所有关联对象 objc_removeAssociatedObjects(self); }
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) { _object_set_associative_reference(object, (void *)key, value, policy); }