7

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?

4

1 回答 1

9

关联对象的代码 在 Objective-C 运行时的objc-references.mm中。

如果我理解正确,有一个全局哈希映射(static AssociationsHashMap *_mapin class AssociationsManager)将对象的地址(“伪装”为uintptr_t)映射到ObjectAssociationMap.

ObjectAssociationMap存储一个特定对象的所有关联,并在

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

被称为对象的第一次。

ObjectAssociationMap是映射keyvalue和的哈希映射policy

释放对象时,_object_remove_assocations()删除所有关联并在必要时释放值。

于 2013-07-16T14:27:43.800 回答