Using objc_setAssociatedObject with weak references

后端 未结 5 2126
执笔经年
执笔经年 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:24

    After trying it out, the answer is NO.

    I ran the following code under the iOS 6 Simulator, but it would probably have the same behavior with previous iterations of the runtime:

    NSObject *test1 = [NSObject new];
    
    NSObject __weak *test2 = test1;
    
    objc_setAssociatedObject(self, "test", test1, OBJC_ASSOCIATION_ASSIGN);
    
    test1 = nil;
    
    id test3 = objc_getAssociatedObject(self, "test");
    

    In the end, test1 and test2 are nil, and test3 is the pointer previously stored into test1. Using test3 would result in trying to access an object that had already been dealloced.

提交回复
热议问题