0

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?

4

1 回答 1

2

设置和获取对象时使用不同的键。

注意&设置时,而不是获取时。您应该在这两种情况下都使用。

一个好的做法是像这样定义键:

static void* KEY_CONNECTION_MYCLASS = &KEY_CONNECTION_MYCLASS;

这样,您的拼写错误就无关紧要了。不过改正错别字就好了。

于 2014-07-15T18:25:04.793 回答