如何通过类别扩展添加属性

2025-12-17 13:54:29
推荐回答(1个)
回答1:

// Declaration

@interface MyObject (ExtendedProperties)
@property (nonatomic, strong, readwrite) id myCustomProperty;
@end

// Implementation

static void * MyObjectMyCustomPorpertyKey = (void *)@"MyObjectMyCustomPorpertyKey";

@implementation MyObject (ExtendedProperties)

- (id)myCustomProperty
{
return objc_getAssociatedObject(self, MyObjectMyCustomPorpertyKey);
}

- (void)setMyCustomProperty:(id)myCustomProperty
{
objc_setAssociatedObject(self, MyObjectMyCustomPorpertyKey, myCustomProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end