如何在对象内使用objc_setAssociatedObject/objc_getAssociatedObject? [英] How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?

查看:98
本文介绍了如何在对象内使用objc_setAssociatedObject/objc_getAssociatedObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在类别实现中使用objc_setAssociatedObject/objc_getAssociatedObject将模拟实例变量存储在setter方法中,那么我将如何访问getter方法中的键,因为在setter方法中声明的任何变量都将超出getter的范围方法?

If I use objc_setAssociatedObject/objc_getAssociatedObject inside a category implementation to store a simulated instance variable in a setter method, how would I access the key in the getter method since any variables declared in the setter method would be outside the scope of the getter method?

为了明确起见,如果要使用以下模式,应在哪里声明STRING_KEY,以便可以在setter和getter方法中使用它.

To clarify, if I were to use the following pattern, where should I declare STRING_KEY so that I could use it in both the setter and the getter method.

@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的内容……这只会浪费内存.

Declare a static variable so that you can use its address as the key. The call to objc_setAssociatedObject takes a void* and only the address of your static variable is actually used, not the contents of a NSString... that is only wasting memory.

您只需要添加:

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

这篇关于如何在对象内使用objc_setAssociatedObject/objc_getAssociatedObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆