Objective-C forwardInvocation:

ma1*_*w28 4 objective-c method-missing nsobject

我经常这样做:

CoolViewController *coolViewController = [[CoolViewController alloc] init];
[self.navigationController pushViewController:coolViewController animated:YES];
[coolViewController release];
Run Code Online (Sandbox Code Playgroud)

在一个类别中UINavigationController,我将如何覆盖,forwardInvocation:以便我可以改为:

[self.navigationController pushCoolViewControllerAnimated:YES];
Run Code Online (Sandbox Code Playgroud)
  1. 请在答案中包含相关代码,而不仅仅是解释.谢谢!

  2. 请随意评论这是否是一种好的做法.我也问这个用于教育目的,但在我看来,在这种情况下,代码的简化可能会超过处理时间和内存使用的不明显(正确?)成本.此外,我来自Ruby背景,喜欢使用动态编程来简化事物,例如find_by_nameRails中的动态查找器(例如).

  3. 如果您可以pushCoolViewControllerAnimated:withBlock在初始化视图控制器后实现并调用块,则允许我在创建的视图控制器上设置某些实例变量.

更新:我记得ARC即将推出.因此,这个具体示例可能不那么有用,但仍然是一个很好的练习/示例,可以在其他情况下使用,例如,Core Data的动态查找器和传递块来配置NSFetchRequest.

Jer*_*man 14

使用Objective-C运行时编程指南中描述的动态方法解析机制,具体来说,+[NSObject resolveInstanceMethod:]:

@implementation UINavigationController (FWD)
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    NSString *name = NSStringFromSelector(sel);
    NSString *prefix = @"push";
    NSString *suffix = @"Animated:";
    if ([name hasPrefix:prefix] && [name hasSuffix:suffix]) {
        NSRange classNameRange = {[prefix length],
            [name length] - [prefix length] - [suffix length]}
        NSString *className = [name substringWithRange:classNameRange];
        Class cls = NSClassFromString(className);
        if (cls) {
            IMP imp = imp_implementationWithBlock(
            ^(id me, BOOL animated) {
                id vc = [[cls alloc] init];
                [me pushViewController:vc animated:animated];
                [vc release];
            });
            class_addMethod(cls, sel, imp, "v@:c");
            return YES;
        }
    }
    return [super resolveInstanceMethod:sel];
}
@end
Run Code Online (Sandbox Code Playgroud)

当然,如果UINavigationController已经使用+resolveInstanceMethod:,你现在已经打破了它.在子类中执行此操作UINavigationController,或使用方法调配以启用调用原始实现,将解决该问题.

接受创建后块的版本是一个简单的扩展(更改块参数,更改类型编码,更改选择器名称模式以及如何提取目标类名).