Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does objc_setAssociatedObject work? [duplicate]

As we know, we can add a variable in Objective-C using a category and runtime methods like objc_setAssociatedObject and objc_getAssociatedObject. For example:

#import <objc/runtime.h>
@interface Person (EmailAddress)
@property (nonatomic, readwrite, copy) NSString *emailAddress;
@end

@implementation Person (EmailAddress)

static char emailAddressKey;

- (NSString *)emailAddress {
    return objc_getAssociatedObject(self, 
                                    &emailAddressKey);
}

- (void)setEmailAddress:(NSString *)emailAddress {
   objc_setAssociatedObject(self, 
                            &emailAddressKey,
                            emailAddress,
                            OBJC_ASSOCIATION_COPY);
}
@end

But does anybody know what does objc_getAssociatedObject or objc_setAssociatedObject do? I mean, where are the variable we add to the object(here is self) stored? And the relationship between variable and self?

like image 767
foogry Avatar asked Jul 16 '13 13:07

foogry


1 Answers

The code for associated objects is in objc-references.mm in the Objective-C runtime.

If I understand it correctly, there is one global hash map (static AssociationsHashMap *_map in class AssociationsManager) that maps the address of an object ("disguised" as uintptr_t) to an ObjectAssociationMap.

ObjectAssociationMap stores all associations for one particular object and is created when

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)

is called the first time for an object.

ObjectAssociationMap is a hash map that maps the key to value and policy.

When an object is deallocated, _object_remove_assocations() removes all associations and releases the values if necessary.

like image 136
Martin R Avatar answered Oct 17 '22 07:10

Martin R