6-关联对象

2018-07-31  本文已影响0人  今晚打老虎_9527

属性

#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

关联对象

#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
上一篇 下一篇

猜你喜欢

热点阅读