I'm studying ARC. And now about zeroing weak pointer. OK I understood all the features. The semantic of weak reference is just same with weak reference of GC system, but you know, Objective-C doesn't use GC (except special case) so I can't understand how this works.
I'm a little complicated guy, so I need to know underlying implementation principal to accept the feature to use. But the problem is it's very hard to find document which describes the principal of zeroing-weak pointer :(
IMO, the only way to make this work is tracking and keeping all pointers referencing itself at runtime, and setting them all nil
when its referencing count becomes 0
. But this looks too heavy and stupid. I believe a lot better solution used in actual ARC implementation.
Can you help me to find the documentation? Or direct description would be more great!
It's explained here:
http://mikeash.com/pyblog/friday-qa-2010-07-16-zeroing-weak-references-in-objective-c.html
Spoiler:
It works pretty much how you'd think. Every class maintains a set of addresses of weak pointers that are pointing to it, and when its dealloc is called it sets them all to zero.
It may seem dumb, but it's fast because there's no "tracking" involved, ARC just inserts the code to add a pointer to that set every time the object is assigned to a new weak reference.
It's actually much more efficient than the trickery involved in Garbage collection, which basically involves wading through the heap on a background thread looking for pointers and keeping stock of what they're pointing to.
Implemented by a global hash table in runtime. Apple source: https://opensource.apple.com/source/objc4/objc4-647/runtime/objc-weak.mm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With