iphone - NSInvocation 意外异常

标签 iphone ios objective-c exception nsinvocation

以下代码抛出异常。

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/

相关文章:

iphone - 如何将使用iOS SDK拍摄的照片添加到用户的相机胶卷中?

ios - 如何在 iOS 中使用预设的 cookie 或 header 在 Safari 中打开 URL?

iphone - 如何修复 iOS 7 上的 UITableView 分隔符?

ios - 获取非本地化字符串

iphone - 设备上的 NSTimer 比模拟器上的慢

iphone - 在sqlite数据库中插入大量数据需要很长时间

ios - 为什么导航 View Controller 返回零 View Controller ?

ios - Swift:如何检查我的应用程序是否具有 WLAN 权限以及设备是否已连接到 WIFI 源?

ios - 在 Xcode5.1 中构建一个在 Xcode 6 GM 中修改的项目,用于测试旧版本的 iOS

iphone - UIButton - 我们应该释放还是不释放?