George Taskos George Taskos - 1 year ago 106
iOS Question

objc_getAssociatedObject suddenly starts returning nil

I have a category for the NSURLConnection and I use associated objects to extend the class to keep a reference to a custom class of mine so I can get later in other context when delegate and forward the call to the real target later. This way I can modify the desired data in certain points of runtime.

But for a reason when everything used to work properly, suddenly the objc_getAssociatedObject returns nil, meaning I don't get back my associated object and the whole process stops.

My code:


static MyClass* GetConnectionMyClass(NSURLConnection* connection)
return (MyClass*)
objc_getAssociatedObject(connection, KEY_CONNECTION_MYCLASS);

static void AttachConnectionMyClass(NSURLConnection* connection, MyClass* myClass)

And how I access the above functions from other static functions.

When I set the associated object:

NSURLConnection* connection = (NSURLConnection*) self;
AttachConnectionMyClass(connection, myClass);

Get the associated object:

NSURLConnection* connection = (NSURLConnection*)self;
MyClass* myClass = GetConnectionMyClass(connection);
if (myClass)
NSLog(@"MyClass is NOT NIL");
NSLog(@"MyClass is NIL");

Result always is "MyClass is NIL". As I mentioned this was working properly and stopped with no reason that comes to my mind.

What do you think?

Answer Source

You are using different keys when setting and getting the object.

Notice the & when setting, but not when getting. You should use in both cases.

A good practice is to define the key like so:


This way, your typo would not have mattered. But it's good to fix typos.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download