简体   繁体   中英

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 void* KEY_CONNECTION_MYCLASS;

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

static void AttachConnectionMyClass(NSURLConnection* connection, MyClass* myClass)
{
    objc_setAssociatedObject(connection,
                         &KEY_CONNECTION_MYCLASS,
                         myClass,
                         OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

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");
}
else
{
   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?

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:

static void* KEY_CONNECTION_MYCLASS = &KEY_CONNECTION_MYCLASS;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM