Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid extra static variables for associated objects keys

When using associated objects, an Objective-C runtime feature available starting from iOS 4 and OSX 10.6, it's necessary to define a key for storing and retrieving the object at runtime.

The typical usage is defining the key like follows

static char const * const ObjectTagKey = "ObjectTag";

and then use is to store the object

objc_setAssociatedObject(self, ObjectTagKey, newObjectTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

and retrieve it

objc_getAssociatedObject(self, ObjectTagKey);

(example taken by http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/)

Is there a cleaner way to define the associated object key, that doesn't involve the declaration of extra variables?

like image 562
Gabriele Petronella Avatar asked Apr 15 '13 17:04

Gabriele Petronella


3 Answers

According to this blog entry by Erica Sadun (whose credits go to Gwynne Raskind), there is.

objc_getAssociatedObject and objc_getAssociatedObject require a key to store the object. Such key is required to be a constant void pointer. So in the end we just need a fixed address that stays constant over time.

It turns out that the @selector implementation provides just about what we need, since it uses fixed addresses.

We can therefore just get rid of the key declaration and simply use our property's selector address.

So if you are associating at runtime a property like

@property (nonatomic, retain) id anAssociatedObject;

we can provide dynamic implementations for its getter/setter that look like

- (void)setAnAssociatedObject:(id)newAssociatedObject {
     objc_setAssociatedObject(self, @selector(anAssociatedObject), newAssociatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)anAssociatedObject {
    return objc_getAssociatedObject(self, @selector(anAssociatedObject));
}

Very neat and definitely cleaner than defining an extra static variable key for every associated object.

Is this safe?

Since this is implementation-dependent, a legitimate question is: will it easily break? Quoting the blog entry

Apple would probably have to implement a completely new ABI for that to happen

If we take those words to be true, it's then reasonably safe.

like image 159
Gabriele Petronella Avatar answered Nov 26 '22 08:11

Gabriele Petronella


If you need access to the key from outside the scope of a single method, a nice pattern for this which leads to more readable code is to create a pointer which simply points to its own address in the stack. For example:

static void const *MyAssocKey = &MyAssocKey;

If you only need access from within the scope of a single method, you can actually just use _cmd, which is guaranteed to be unique. For example:

objc_setAssociatedObject(obj, _cmd, associatedObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
like image 37
Will Pragnell Avatar answered Nov 26 '22 10:11

Will Pragnell


A slight variation on the idea @Gabriele Petronella discussed is to associate a dictionary to every object:

//NSObject+ADDLAssociatedDictionary.h

#import <Foundation/Foundation.h>

@interface NSObject (ADDLAssociatedDictionary)
- (void)addl_setAssociatedObject:(id)object forKey:(id<NSCopying>)key;
- (id)addl_associatedObjectForKey:(id<NSCopying>)key;
@end

//NSObject+ADDLAssociatedDictionary.m

#import <objc/runtime.h>

@interface NSObject (ADDLAssociatedDictionaryInternal)
- (NSMutableDictionary *)addl_associatedDictionary;
@end

@implementation NSObject (ADDLAssociatedDictionary)

- (void)addl_setAssociatedObject:(id)object forKey:(id<NSCopying>)key
{
    if (object) {
        self.addl_associatedDictionary[key] = object;
    } else {
        [self.addl_associatedDictionary removeObjectForKey:key];
    }
}
- (id)addl_associatedObjectForKey:(id<NSCopying>)key
{
    return self.addl_associatedDictionary[key];
}

@end

@implementation NSObject (ADDLAssociatedDictionaryInternal)
const char addl_associatedDictionaryAssociatedObjectKey;
- (NSMutableDictionary *)addl_associatedDictionaryPrimitive
{
    return objc_getAssociatedObject(self, &addl_associatedDictionaryAssociatedObjectKey);
}
- (void)addl_setAssociatedDictionaryPrimitive:(NSMutableDictionary *)associatedDictionary
{
    objc_setAssociatedObject(self, &addl_associatedDictionaryAssociatedObjectKey, associatedDictionary, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSMutableDictionary *)addl_generateAssociatedDictionary
{
    NSMutableDictionary *associatedDictionary = [[NSMutableDictionary alloc] init];
    [self addl_setAssociatedDictionaryPrimitive:associatedDictionary];
    return associatedDictionary;
}

- (NSMutableDictionary *)addl_associatedDictionary
{
    NSMutableDictionary *res = nil;

    @synchronized(self) {
        if (!(res = [self addl_associatedDictionaryPrimitive])) {
            res = [self addl_generateAssociatedDictionary];
        }
    }

    return res;
}
@end

Then in our category on some subclass Derived of NSObject

//Derived+Additions.h

#import "Derived.h"

@interface Derived (Additions)
@property (nonatomic) id anAssociatedObject;
@end

//Derived+Additions.m

#import "NSObject+ADDLAssociatedDictionary.h"

@implementation Derived (Additions)
- (void)setAnAssociatedObject:(id)anAssociatedObject
{
    [self addl_setAssociatedObject:anAssociatedObject forKey:NSStringFromSelector(@selector(anAssociatedObject))];
}
- (id)anAssociatedObject
{
    return [self addl_associatedObjectForKey:NSStringFromSelector(@selector(anAssociatedObject))];
}
@end

One benefit of the associated dictionary approach in general is the added flexibility that comes from being able to set objects for keys that are generated at runtime, not to mention the much nicer syntax.

A benefit particular to using

NSStringFromSelector(@selector(anAssociatedObject))

is that NSStringFromSelector is guaranteed to give an NSString representation of the selector which will always be an acceptable dictionary key. As a result, we don't have to worry at all (though I don't think it's a reasonable concern) about ABI changes.

like image 39
Nate Chandler Avatar answered Nov 26 '22 08:11

Nate Chandler