I am in a situation where I want to dynamically generate getters and setters for a class at runtime (in a similar manner to what NSManagedObject does behind the scenes). From my understanding, this is possible using resolveInstanceMethod: on a specific class. At this point, you would have to use class_addMethod to dynamically add the method based on the selector. I understand this at a theoretical level, but I haven’t delved much into the obj-c runtime, so I was curious if there were any great examples of how to do this. Most of my knowledge comes from this article:
Any thoughts / examples?
The only nice discussion I know is at Mike Ash’s blog post. It’s not that hard, actually.
I once needed to split a big
NSManagedObjectsubclass into two, but decided to keep the fact an implementation detail so that I don’t have to rewrite other parts of my app. So, I needed to synthesize getter and setter which sends[self foo]to[self.data foo], automatically.To achieve that, I did the following:
Prepare the new method, already in my class.
Note that
_cmdhas the selector in it. So, usually,_cmdis either@selector(_getter_)or@selector(_setter_)in these methods, but I’m going to plug the implementation of_getter_as the implementation offoo. Then,_cmdcontains@selector(foo), and thus callsself.data‘sfoo.Write a generic synthesizing method:
Note that this is a class method. So
selfstands for the class. Note also that I didn’t hardcode type encodings (which tells Objective-C runtime what the arguments of the particular method are). The syntax of type encodings is documented, but constructing by hand is very error-prone; I wasted a few days that way until Mike Ash told me to stop it. Generate it using an existing method.Generate forwarders at the earliest possible time:
This generates
foo,setFoo:,bar,setBar:, andbaz,setBaz:.Hope this helps!