The only nice discussion I know is Mike Ash's blog post. This is actually not so difficult.
I once needed to split a large subclass NSManagedObjectinto two, but decided to keep the fact implementation details so that I did not have to rewrite other parts of my application. So, I needed to synthesize getter and setter, which automatically sends [self foo]to [self.data foo].
To do this, I did the following:
Prepare a new method already in my class.
- (id)_getter_
{
return objc_msgSend(self.data, _cmd);
}
- (void)_setter_:(id)value
{
objc_msgSend(self.data, _cmd,value);
}
, _cmd . , _cmd @selector(_getter_), @selector(_setter_) , _getter_ foo. _cmd @selector(foo) , , self.data foo.
:
+(void)synthesizeForwarder:(NSString*)getterName
{
NSString*setterName=[NSString stringWithFormat:@"set%@%@:",
[[getterName substringToIndex:1] uppercaseString],[getterName substringFromIndex:1]];
Method getter=class_getInstanceMethod(self, @selector(_getter_));
class_addMethod(self, NSSelectorFromString(getterName),
method_getImplementation(getter), method_getTypeEncoding(getter));
Method setter=class_getInstanceMethod(self, @selector(_setter_:));
class_addMethod(self, NSSelectorFromString(setterName),
method_getImplementation(setter), method_getTypeEncoding(setter));
}
, . , self . , hardcode ( Objective-C runtime, ). , ; , . .
:
+(void)load
{
for(NSString*selectorName in [NSArray arrayWithObjects:@"foo", @"bar", @"baz",nil]){
[self synthesizeForwarder:selectorName];
}
}
foo, setFoo:, bar, setBar: baz, setBaz:.
, !