基本關聯物件示例

假設我們需要將一個 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";