gpt4 book ai didi

objective-c - 我怎样才能通过消息转发将 "swallow"发送到 "unrecognized selector error"?

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

我正在研究 Objective-C 的“消息转发”。我编写了一个测试程序来验证我是否可以在运行时“吞下”一个无法识别的选择器。所以我这样做了:

- (void) forwardInvocation: (NSInvocation *) anInvocation {
if ([anInvocation selector] == @selector(testMessage)){
NSLog(@"Unknow message");
}
return;
}

但它仍然在运行时抛出“无法识别的选择器”错误。搜索解决方案后,我知道我需要覆盖方法“methodSignatureForSelector:”,所以我编写了另一个名为“Proxy”的代理类和以下方法:

(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
if ([Proxy instancesRespondToSelector: selector]) {
return [Proxy instanceMethodSignatureForSelector: selector];
}
return [super methodSignatureForSelector:selector];
}

但是,实际上,我并不想实现这样的另一个代理类来完成这个方法。我只想忽略这个未知的选择器。但是如果我只是输入这个,它就不起作用:

(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {   
return [super methodSignatureForSelector:selector];
}

所以,我想知道有什么方法可以简单地“吞下”这个错误吗? (不使用异常处理程序,我想要一种类似“转发”的方式)。谢谢!

最佳答案

您可能需要生成一个签名对象,这有点棘手:

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
NSMethodSignature *sig = [super methodSignatureForSelector:selector];
if (!sig) {
if (selector == @selector(testMessage)) {
// Create a signature for our fake message.
sig = [NSMethodSignature signatureWithObjCTypes:"@:"];
}
}
return sig;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
// Do whatever you want with the invocation.
}

最大的问题似乎是 signatureWithObjCTypes: 的参数。参见 Apple's type encoding documentation .每个方法至少有两个参数:id self(类型@)和SEL _cmd(类型:)。

另一种方法是使用虚拟方法,比如 - (void)dummy { } 然后使用 sig = [super methodSignatureForSelector:@selector(dummy)]; 为您的伪造方法获取签名。

关于objective-c - 我怎样才能通过消息转发将 "swallow"发送到 "unrecognized selector error"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034461/

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