views:

88

answers:

2

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?

Edit: 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
+1  A: 

Declare a static (compilation unit-scope) variable at the top level of the source file. It may help to make it meaningful, something like this:

static NSString *MYSimulatedString = @"MYSimulatedString";
Nicholas Riley
edited to clarify
leo
I replaced my answer with one that answers your question, now I know what it is :-)
Nicholas Riley
Thanks! This seems obvious enough. It seems my brain wants to encapsulate everything :).
leo
A: 

Declare a static variable so that you can use its address as the key just like the apple documentation example.
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.

You just need to add:

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
Brent Priddy