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

2025-12-17 17:03:37
推荐回答(2个)
回答1:

没有属性。category一般只使用扩展方法,可以使用全局变量,例如
@inferface MyClass (xxx)
{
int num;
}
- (void)myFunc;
但我曾用时出现莫名奇妙的数据错误,就不再用。

回答2:

// 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