2
是否有可能生成一個Obj-C方法? - 例如:生成一個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);
}