Using objc_setAssociatedObject with weak references

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

    This behavior isn't specified in the docs or headers as best I can tell, so it's likely an implementation detail that you shouldn't count on, even if you were able to discern what the current behavior is. I would guess that it is not zeroed out. Here's why:

    In general, there is no need to nil out references in iVars during -dealloc. If an object is dealloced, it shouldn't matter if its iVars were zeroed out, because any further accessing of the dealloced object or its iVars is, in and of itself, a programming error. In fact, I've heard some argue that it's better to not clear out references during -dealloc, because it will make erroneous accesses more obvious/expose bugs sooner.

    EDIT: Oh, I guess I misread your question. You want "zeroing weak references". Associated storage doesn't appear to support those. You could make a trivial pass-through class with one ivar/property marked as __weak and achieve the same effect that way. A little kludgey, but it'd work.

提交回复
热议问题