Associated objects in Swift, does global key actually produce specific instances?

眉间皱痕 提交于 2019-11-29 07:35:37
Nikolai Ruhe

Objective-C's concept of "associated objects" lets you connect one "target" object instance with one "source" object instance. It's a unidirectional association where only the source knows the target:

objc_setAssociatedObject(source, key, target, ...)

The association uses a key to be able to connect and distinguish any number of associated objects with one source. The keys must obviously be different—but just for one source instance.

Because you have to provide both the key and the source instance to retrieve the associated object, it's not necessary to use really unique keys. The implementation of objc_***AssociatedObject can form a process-unique key by combining the instance pointer and the key.

So for your example, yes, both aoAA and aoBB will return individual values per each UIViewController instance, even though keyA and keyB are global.

To be absolutely clear, you do need different keys for each associated object in a given extension. So, aoAA and aoBB each need their own key, as shown in the example code (to wit, the pointers to keyA and keyB). But as is asked in the question it's correct have only one key for each associated object, no matter how many conforming classes the extension is used in.

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