Nicolas Manzini Nicolas Manzini - 3 months ago 14
iOS Question

if(objc_getAssociatedObject(self, &Key)) return true for nil object

How can I test that

objc_getAssociatedObject
is
nil
? The following says element is not
nil
but the associated object has never been set before nor been accessed.

static char orderedElementKey = 11;

if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
NSLog(@"element is not nil");
return objc_getAssociatedObject(self, &orderedElementKey);
}
NSLog(@"elelement was nil !");

Answer
static char orderedElementKey = 11;
//objc_setAssociatedObject(self, &orderedElementKey, @"value", OBJC_ASSOCIATION_RETAIN);

if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
    NSLog(@"Element: %@", objc_getAssociatedObject(self, &orderedElementKey));
}
else
{
    NSLog(@"element nil !");
}

prints "Element nil !" while removing the comment on objc_setAssociatedObject() prints "Element: value". How is your code different?