如果我在类别实现中使用 objc_setAssociatedObject/objc_getAssociatedObject 将模拟实例变量存储在 setter 方法中,我将如何访问 getter 方法中的键,因为在 setter 方法中声明的任何变量都将超出 getter 的范围方法?
编辑:澄清一下,如果我要使用以下模式,我应该在哪里声明 STRING_KEY 以便我可以在 setter 和 getter 方法中使用它。
@interface NSView (simulateVar)
-(void)setSimualtedString:(NSString *)myString;
-(NSString *)simulatedString;
@end
@implementation NSView (simulateVar)
-(void)setSimualtedString: (NSString *)myString
{
objc_setAssociatedObject(self, &STRING_KEY, myString, OBJC_ASSOCIATION_RETAIN);
}
-(NSString *)simulatedString
{
return (NSString *)objc_getAssociatedObject(self, &STRING_KEY);
}
@end
最佳答案
声明一个静态变量,以便您可以使用它的地址作为键。 对 objc_setAssociatedObject 的调用需要一个 void* 并且仅实际使用静态变量的地址,而不是 NSString 的内容......这只会浪费内存。
你只需要添加:
static char STRING_KEY; // global 0 initialization is fine here, no
// need to change it since the value of the
// variable is not used, just the address
关于objective-c - 如何在对象内使用 objc_setAssociatedObject/objc_getAssociatedObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2846218/