What is objc_setAssociatedObject() and in what cases should it be used?

后端 未结 4 1165
有刺的猬
有刺的猬 2020-11-28 20:26

In a project I have taken on, the original author has opted to use objc_setAssociatedObject() and I\'m not 100% clear what it does or why they decided to use it

4条回答
  •  猫巷女王i
    2020-11-28 21:05

    objc_setAssociatedObject adds a key value store to each Objective-C object. It lets you store additional state for the object, not reflected in its instance variables.

    It's really convenient when you want to store things belonging to an object outside of the main implementation. One of the main use cases is in categories where you cannot add instance variables. Here you use objc_setAssociatedObject to attach your additional variables to the self object.

    When using the right association policy your objects will be released when the main object is deallocated.

提交回复
热议问题