How to “fake” ivars in an Obj-C category (iPhone)

后端 未结 5 1122
鱼传尺愫
鱼传尺愫 2021-02-09 16:13

Update:

iPhone OS 3.1 has associated objects. However, the iPhone simulator does not. If you want to test associated objects code in the simulator, you should file a bug

5条回答
  •  死守一世寂寞
    2021-02-09 16:46

    There are no good ways to do this in a generic category.

    You can easily add data for an object by having a global NSMutableDictionary that maps from any arbitrary NSObject to whatever data you want. The problem is there is no way to know when the object is deallocated, so you cannot tell (in general) when the data goes stale.

    The only generic way to solve this is to use method swizzling to replace the NSObject dealloc method to report the deallocation of the object and release your associated data. I'm sure someone has done this, but its such a hideous hack it would be very hard to recommend as a valid appropach.

    Now, if your objects in questions have some other way to monitor life cycle (ie, some deallocation hook, like a delegate objectWillClose method of some sort), then you can hook in to that to release your associated data and that would make the technique quite straight forward and legitimate.

提交回复
热议问题