按钮的动作导致“无效的选择器”崩溃 - 为什么?

时间:2011-11-28 17:31:12

标签: objective-c ios cocoa-touch uibutton target-action

当按下我创建的按钮时,此代码会导致“无效选择器”错误。从{

>获取test函数的位置

的main.m

mainScreen = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
[self.view addSubview:mainScreen];

TaskButtons *tB = [[TaskButtons alloc] init];
[mainScreen addSubview:[tB TaskStart]]; 

TaskButtons.m

- (UIButton*)TaskStart {
   CGRect buttonFrame = CGRectMake(500, 206, 400, 35);
   UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
   button.frame = buttonFrame;
   [button setTitle:@"Task Button" forState:UIControlStateNormal];
   button.backgroundColor = [UIColor clearColor];
   button.titleLabel.textAlignment = UITextAlignmentLeft;
   button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
   [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
   [button addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
   return button;
 }

- (void)test{
   NSLog(@"test line");
}

似乎没有调用test函数。这里没有将按钮的target设置为self意味着它应该在TaskButtons类中查找名为test的函数吗?

2 个答案:

答案 0 :(得分:0)

问题是ARC过早地释放实例化对象。所以为了解决这个问题,我需要更长时间地保留它。

Main.h

#import "TaskButtons.m"
@interface ViewController : UIViewController {
     TaskButtons *tB;
}

@property (nonatomic, retain) TaskButtons *tB;

答案 1 :(得分:0)

[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];

- (void)test:(id)sender{
NSLog(@"test line");
}

语法问题:)在你的代码中替换这些行。