是否可以生成 Obj-C 方法?- 例如:
- (void)doSomething:(BOOL)isLater
{
if (isLater == FALSE)
{
NSLog(@"Not Later");
} else {
NSLog(@"Is Later");
}
}
我专门谈论生成逻辑,我有一些可以创建类并添加现有方法的代码,但我想知道是否可以为方法本身生成逻辑并将其添加到方法中?
static NSString *Description(id self, SEL _cmd)
{
return @"My Description Method";
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
Class mySubclass = objc_allocateClassPair([NSObject class], "MySubclass", 0);
// grab NSObject's description signature so we can borrow it
Method description = class_getInstanceMethod([NSObject class],
@selector(description));
const char *types = method_getTypeEncoding(description);
// now add
class_addMethod(mySubclass, @selector(description), (IMP)Description, types);
objc_registerClassPair(mySubclass);
id myInstance = [[mySubclass alloc] init];
NSLog(@"%@", myInstance);
}