首页 > 代码库 > ##oc在类别里给类加属性以及原理

##oc在类别里给类加属性以及原理

oc在类别里给类加属性以及原理

如何在类别里给类加属性呢,有鸭子模样的我们就认为他是鸭子了.

@interface NSObject (XY)
@property (nonatomic, strong) id                tempObject;
@end

@implementation NSObject (XY)

@dynamic tempObject;

- (id)tempObject
- {
    id object = objc_getAssociatedObject(self, NSObject_key_tempObject);

    return object;
}

- (void)setTempObject:(id)tempObject
- {
    [self willChangeValueForKey:@"tempObject"];
    objc_setAssociatedObject(self, NSObject_key_tempObject, tempObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"tempObject"];
}
@end

属性取变量是直接偏移地址得到,关联是取了2次map.

下面来看一下set get 还有dealloc时候发生的事情吧

void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
#if SUPPORT_GC
    if (UseGC) {
        if ((policy & OBJC_ASSOCIATION_COPY_NONATOMIC) == OBJC_ASSOCIATION_COPY_NONATOMIC) {
            value = http://www.mamicode.com/objc_msgSend(value, SEL_copy);>

##oc在类别里给类加属性以及原理