Using objc_setAssociatedObject with weak references

后端 未结 5 2140
执笔经年
执笔经年 2020-12-23 21:34

I know that OBJC_ASSOCIATION_ASSIGN exists, but does it zero the reference if the target object is dealloced? Or is it like the old days where that reference needs to get n

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 22:14

    As ultramiraculous demonstrated, OBJC_ASSOCIATION_ASSIGN does not do zeroing weak reference and you risk to access a deallocated object. But it’s quite easy to implement yourself. You just need a simple class to wrap an object with a weak reference:

    @interface WeakObjectContainer : NSObject
    @property (nonatomic, readonly, weak) id object;
    @end
    
    @implementation WeakObjectContainer
    - (instancetype) initWithObject:(id)object
    {
        if (!(self = [super init]))
            return nil;
    
        _object = object;
    
        return self;
    }
    @end
    

    Then you must associate the WeakObjectContainer as OBJC_ASSOCIATION_RETAIN(_NONATOMIC):

    objc_setAssociatedObject(self, &MyKey, [[WeakObjectContainer alloc] initWithObject:object], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    

    and use the object property to access it in order to get a zeroing weak reference:

    id object = [objc_getAssociatedObject(self, &MyKey) object];
    

提交回复
热议问题