0

以下代码引发异常。

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。 有人可以解释我怎么了?

更新:

此代码代码给我响应消息。所以我的类对象是正确的 [vcClass instancesRespondToSelector:viewWillAppearSEL] 吗?NSLog(@"响应") : NSLog(@"不响应");

我也马上崩溃了[invocation setSelector:viewWillAppearSEL];。这就是为什么我用 NSInvocation 将主题标题称为Unexpected 异常

更新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");
}
4

2 回答 2

1

您的代码的一个问题是您传递给的类型编码class_addMethod()。这种类型编码必须包括:1)返回类型,2)self_cmd(前两个隐藏参数)的类型,然后是 3)所有其他参数的类型。

对于类似的方法- (void)viewWillAppear:(BOOL)animated,类型编码应该是字符串

v@:c

  • v-- for void, 返回类型
  • @-- for id, 输入self
  • :-- for SEL, 输入_cmd
  • c——因为char,就是这样BOOL。这是你做的时候得到的@encode(BOOL)
于 2013-05-18T09:45:59.657 回答
1

布尔 *arg1;

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setSelector:viewWillAppearSEL];
[invocation setArgument:&arg1 atIndex:2];   // argument indexing is offset by 2 hidden args
于 2013-05-10T12:43:10.313 回答