基本关联对象示例

假设我们需要将一个 NSString 对象添加到 SomeClass(我们不能继承子类)。

在此示例中,我们不仅创建了一个关联对象,还将其包装在类别中的计算属性中,以获得额外的整洁

#import <objc/runtime.h>

@interface SomeClass (MyCategory)
// This is the property wrapping the associated object. below we implement the setter and getter which actually utilize the object association
@property (nonatomic, retain) NSString *associated;
@end

@implementation SomeClass (MyCategory)

- (void)setAssociated:(NSString *)object {
    objc_setAssociatedObject(self, @selector(associated), object,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)associated {
    return objc_getAssociatedObject(self, @selector(associated));
}

现在使用该属性就像这样容易

SomeClass *instance = [SomeClass alloc] init];
instance.associated = @"this property is an associated object under the hood";