下面的代码引发异常。
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:atIndex::index (1)超出范围-1,-1
附加信息: iOS5,ARC。有人能解释我出什么事了吗?
更新:
这段代码为我提供了响应消息。所以我的类对象是正确的-- vcClass实例--viewWillAppearSEL:viewWillAppearSEL?NSLog(@"responds"):NSLog(@“”)
我在[invocation setSelector:viewWillAppearSEL];之后马上就要崩溃了。这就是为什么我将主题标题称为NSInvocation意外异常的原因。
UPDATED2:
也是我的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");
}发布于 2013-05-18 09:45:59
代码的一个问题是要传递给class_addMethod()的类型编码。这种类型编码必须包括: 1)返回类型,2) self和_cmd的类型(前两个隐藏参数),3)所有其他参数的类型。
对于像- (void)viewWillAppear:(BOOL)animated这样的方法,类型编码应该是字符串
v@:c
v --对于void,返回类型@ --对于id,键入self: --对于SEL,键入_cmdc --对char来说,BOOL就是这样。这就是你做@encode(BOOL)的时候得到的发布于 2013-05-10 12:43:10
BOOL *arg1 1;
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setSelector:viewWillAppearSEL];
[invocation setArgument:&arg1 atIndex:2]; // argument indexing is offset by 2 hidden argshttps://stackoverflow.com/questions/16482302
复制相似问题