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

后端 未结 4 1164
有刺的猬
有刺的猬 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条回答
  •  误落风尘
    2020-11-28 21:00

    To answer your revised question:

    What is the point in associating the device with the view controller if it's already an instance variable?

    There are several reasons why you might want to do this.

    • the Device class doesn't have a controller instance variable, or property and you can't change it or subclass it e.g. you don't have the source code.
    • you want two controllers associated with the device object and you can't change the device class or subclass it.

    Personally, I think it is very rare to need to use low level Objective-C runtime functions. This looks like a code smell to me.

提交回复
热议问题