I am trying to make a key for use in objc_setAssociatedObject, as in this question:
How to use objc_setAssociatedObject / objc_getAssociatedObject inside an object?
I have a MyConstants.h file that defines
static NSString *myConstant = @"MyConstant";
This file is then included in MyFramework through MyFramework.h
#import ...; #import "MyConstants.h" #import ...;
Then in my project, the structure is included in all files through the .pch header.
#import <Cocoa/Cocoa.h> #import <MyFramework/MyFramework.h>
Everything works as expected. The problem is that when I call objc_setAssociatedObject or objc_getAssociatedObject with myConstant as the key, this does not work. The reason is clear enough from the journal:
- (void)doSomething:(id)key { //Gets called with myConstant NSLog(@"Associating with key at %p", &key); objc_setAssociatedObject(self, &key, object, policy); } - (void)doSomethingElse:(id)key { //Gets called with myConstant NSLog(@"Seeking association for key at %p", &key); NSLog(@"Will find %@", objc_getAssociatedObject(self, &key)); }
Which magazines:
Associating with key at 0x7fff5fbfecdf Seeking association for key at 0x7fff5fbfecef Will find (null)
You will notice that the pointers are shifted.
However, when calling the same method, the same pointers are displayed again. It is as if the constant IS is a constant in the file that imports it, but not for the entire project .
Q: How can I correctly define and import headers with constants so that the constant is in a constant place in memory?