I want to programmatically associate code with selectors. I am not clear on how to do that in Objective C. In Ruby, I might override method_missing
. In Common Lisp, I might define a macro. In Objective C, I can get part of the way there with @dynamic
properties, but I'm unclear on how to actually implement them.
Here's a concrete example: I want to use an NSMutableDictionary
to persistently store parts of my object. My class has two methods that handle the basic functionality, and a bunch of dynamic properties (matching @property
s exist in @interface
):
@dynamic name;
@dynamic age;
@dynamic favoriteColor;
- (id)accessor:(NSString*)name {
return [[self dict] objectForKey:name];
}
- (void)mutator:(NSString*)name value:(id)value{
[[self dict] setObject:value forKey:name];
[[self dict] writeToFile:[self filename] atomically:YES];
}
Now I am looking for a way to translate a call like
[myInstance setName:@"iter"];
into
[self mutator:@"name" value@"iter"];
I wonder if there is an idiomatic way to do that in ObjC.