以下代码抛出异常。
vcClass
是一个 Class
对象(继承自 UIViewController
)。 Self
包含 我的实现 viewWillAppear:
SEL viewWillAppearSEL = @selector(viewWillAppear:);
IMP viewWillAppearWithSuperIMP = [self methodForSelector:viewWillAppearSEL];
class_addMethod(vcClass, viewWillAppearSEL, viewWillAppearWithSuperIMP, @encode(BOOL));
NSMethodSignature *methodSignature = [vcClass instanceMethodSignatureForSelector:viewWillAppearSEL];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setSelector:viewWillAppearSEL];
留言:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[NSInvocation setArgument:atIndex:]: index (1) out of bounds [-1, -1]”
附加信息:iOS5、ARC。 谁能给我解释一下哪里出了问题?
更新:
此代码代码给我 responses 消息。所以我的类对象是正确的 [vcClass 实例响应选择器:viewWillAppearSEL] ? NSLog(@"响应") : NSLog(@"不响应");
此外,我在 [invocation setSelector:viewWillAppearSEL];
之后立即崩溃。这就是为什么我将主题标题称为 Unexpected exception with NSInvocation。
更新2:
还有我的实现 viewWillAppear:
- (void)viewWillAppear:(BOOL)animated {
Class parentViewController = [self superclass];
void (*superViewWillAppear)(id, SEL, BOOL) =(void(*)(id, SEL, BOOL))class_getMethodImplementation(parentViewController, _cmd);
superViewWillAppear(self, _cmd, animated);
NSLog(@"view will appear with super");
}
最佳答案
代码的一个问题是您传递给 class_addMethod()
的类型编码。此类型编码必须包括:1) 返回类型,2) self
和 _cmd
的类型(前两个隐藏参数),然后 3) 所有的类型其他参数。
对于像- (void)viewWillAppear:(BOOL)animated
这样的方法,类型编码应该是字符串
v@:c
v
-- 对于void
,返回类型@
--id
,输入self
:
-- 对于SEL
,键入_cmd
c
-- 对于char
,这就是BOOL
。这是您执行@encode(BOOL)
时得到的结果
关于iphone - NSInvocation 意外异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16482302/