未识别的选择器发送到实例

3

有人知道我为什么会收到这个错误吗?

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CustomRaisedTabViewController cancel:]: unrecognized selector sent to instance 0x4d321e0'

这是出错的代码。在我的CustomTabViewController中发生的。当我点击“取消”按钮时就会出现错误。

-(IBAction)showPostModalViewController {

PostActionModalViewController *addController = [[PostActionModalViewController alloc] 
                                                initWithNibName:@"PostActionModalView" bundle:nil];

// Configure the PostAddViewController. In this case, it reports any
// changes to a custom delegate object.

addController.delegate = self;



// Create the navigation controller and present it modally.

UINavigationController *navigationController = [[UINavigationController alloc]
                                                initWithRootViewController:addController];

[self presentModalViewController:navigationController animated:YES];

UIBarButtonItem *cancelButton =
[[UIBarButtonItem alloc] initWithTitle: @"Cancel"
                                 style: UIBarButtonItemStylePlain
                                target: self
                                action: @selector(cancel:)];
addController.navigationItem.rightBarButtonItem = cancelButton;
[cancelButton release];


//[self presentModalViewController:addController animated:true];
[navigationController release];

[addController release];
}

-(IBAction)cancel {
    [self.parentViewController dismissModalViewControllerAnimated:YES];
}

1
你试图调用一个带有参数的选择器,而实际的方法却没有参数。只需在@selector后面删除冒号,它就可以正常工作了。或者,你可以按照jer的建议修改你的cancel操作。 - sudo rm -rf
3个回答

9
因为cancel:方法不是你定义的cancel。将你的cancel操作更改为以下内容:
- (IBAction)cancel:(id)sender {
    ...
}

我是一个新手... 当我取消时... 它会知道关闭/销毁addController和navigationController吗? - jdog
不能保证立即发生。但是假设您遵循内存管理规则,那么在某个时刻,当系统认为合适时,肯定会发生。 - jer
1
仅仅删除@selector指令中多余的冒号不是更简单吗?因为OP的“cancel”方法无论如何都会忽略该参数,所以为什么要传递它呢? - jlehr
按照惯例,操作需要一个发送者参数,如果你开始偏离惯例,很容易开始出错,因为有时你使用发送者,有时你不使用。随着时间和开发人员之间的一致性使用,消除了很多潜在的错误可能性。 - Kendall Helmstetter Gelner

1
action: @selector(cancel:) 

对于需要带参数的动作选择器!cancel:这意味着它将使用另一个参数。请更改您的方法为:
-(IBAction)cancel:(id)sender{
// Do wat you want
}

or

-(IBAction)cancel:(UIButton *)btnSender{
/// Do what you want
}

0

你需要修改取消方法的签名

-(IBAction)cancel:(id)sender
 { 
   [self.parentViewController dismissModalViewControllerAnimated:YES]; 
 }

当您在初始化期间将操作添加到cancelButton时,指定了“cancel:”选择器,这意味着它将调用具有一个参数(发送方按钮)的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接