The key for objc_setAssociatedObject saves the change of address

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?

+6
source share
2 answers

If two files have static char something , each of them will have its own copy - they do not represent the same part of memory. If you want two files to have access to the key, you should do this in your header:

 extern const char MyConstantKey; 

And this is in one implementation file (.c or .m):

 const char MyConstantKey; 

This defines a single, single- char shared memory location to which all files will be displayed when you use &MyConstantKey .

+8
source

I edited the original post to show what I think of the error. Another answer to the poster might well be a great solution, but as I solved the problem, it was like this:

As the & symbol indicates, I passed the key directly to the methods, as in myMethod: (id). One way or another, in different cases, refusing to reference this pointer was different. Just changing all the methods to myMethod: (void *) and skipping the key, the problem immediately disappeared. Or ensuring that I used a static char and not a static NSString *

I do not understand it completely, but it works.

0
source

Source: https://habr.com/ru/post/893701/


All Articles