I'm trying to make a key for use in objc_setAssociatedObject, as in this question:
How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?
I have a MyConstants.h file which defines
static NSString *myConstant = @"MyConstant";
This file is then included in MyFramework via MyFramework.h
#import ...;
#import "MyConstants.h"
#import ...;
Then in my project, the framework is included in all files via the .pch header.
#import <Cocoa/Cocoa.h>
#import <MyFramework/MyFramework.h>
This all works as expected. The problem is that when I call objc_setAssociatedObject or objc_getAssociatedObject with myConstant as the key, it doesn't work. The reason is clear enough from the log:
- (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 logs:
Associating with key at 0x7fff5fbfecdf
Seeking association for key at 0x7fff5fbfecef
Will find (null)
You'll notice that the pointers shift.
However, calling the same method again shows the same pointers. It's as if the constant IS a constant, in the file that imports it, but not for the whole project.
Q: How can I correctly define and import headers with constants so that a constant is actually at a constant place in memory?
If two files have static char something
, each one will have its own copy--they do not represent the same piece of memory. If you want two files to have access to the key, you must instead do this in your header:
extern const char MyConstantKey;
And this in one implementation file (.c or .m):
const char MyConstantKey;
This defines a single one-char
-wide location in memory, to which all files will point when you use &MyConstantKey
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With