How does the ARC's zeroing weak pointer behavior implemented?

只谈情不闲聊 提交于 2019-11-30 13:21:30

问题


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!


回答1:


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.




回答2:


Implemented by a global hash table in runtime. Apple source: https://opensource.apple.com/source/objc4/objc4-647/runtime/objc-weak.mm



来源:https://stackoverflow.com/questions/8859666/how-does-the-arcs-zeroing-weak-pointer-behavior-implemented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!