gpt4 book ai didi

Objective-C forwardInvocation :

转载 作者:太空狗 更新时间:2023-10-30 03:57:18 26 4
gpt4 key购买 nike

我经常这样做:

CoolViewController *coolViewController = [[CoolViewController alloc] init];
[self.navigationController pushViewController:coolViewController animated:YES];
[coolViewController release];

我如何在 UINavigationController 的类别中覆盖 forwardInvocation: 以便我可以改为:

[self.navigationController pushCoolViewControllerAnimated:YES];
  1. 请在您的回答中包含相关代码,而不仅仅是解释。谢谢!

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

  3. 如果您可以实现 pushCoolViewControllerAnimated:withBlock 并在初始化 View Controller 后调用 block ,允许我在创建的 View Controller 上设置某些实例变量,则加分。

更新:我只记得 ARC 即将推出。所以这个具体的例子可能没有那么有用,但仍然是一个很好的练习/例子,可以在其他情况下使用,例如,核心数据的动态查找器和传递一个 block 来配置 NSFetchRequest

最佳答案

使用Objective-C Runtime Programming Guide中描述的动态方法解析机制,具体来说,+[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

当然,如果 UINavigationController 已经使用了 +resolveInstanceMethod:,那么您现在已经破坏了它。在 UINavigationController 的子类中执行此操作,或使用方法调配来启用调用原始实现,将解决该问题。

接受创建后 block 的版本是一个简单的扩展(更改 block 参数、更改类型编码、更改选择器名称模式以及如何提取预期的类名)。

关于Objective-C forwardInvocation :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com