Search code examples
objective-cautomatic-ref-countingweak-referencesobjective-c-runtime

Adding a weak ivar to a Objective-C class using the runtime


Is it possible to add a zeroing weak ref (in the ARC sense, not GC) instance variable to a class created using the runtime? If so how?

There is a function called class_setWeakIvarLayout() which seems to be related to this but the documentation (both for this function and the non-weak counterpart) is very thin unfortunately.


Solution

  • class_setWeakIvarLayout() is used under GC. I'm not sure it is used under ARC at all. In any case, you can't change the layout of a class at runtime, including adding arbitrary instance variables (though you can add ivars to a class and recompile without recompiling subclasses because of the modern runtime).

    See Associated objects. They provide most of what you want, maybe all (I'm not sure if zeroing-weak is supported directly -- not, you'll need to find an alternative solution).

    http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocAssociativeReferences.html


    Ahh -- OK. Thanks for the clarification. I'm not sure if you can dynamically set the zeroing-weak ARC behaviors via API. The source for the runtime and compiler are available, though.

    Note that you can pretty easily fake zeroing weak under non-ARC environments by setting up a class that implements -dealloc to do whatever cleanup you need, associating instances with objects that need to trigger said cleanup on deallocation and making sure nothing else retains the object that has the custom -dealloc notification hook. It is a bit fragile, but it works.