Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 按钮';s行动导致;无效选择器";撞车,为什么?_Objective C_Ios_Cocoa Touch_Uibutton_Target Action - Fatal编程技术网

Objective c 按钮';s行动导致;无效选择器";撞车,为什么?

Objective c 按钮';s行动导致;无效选择器";撞车,为什么?,objective-c,ios,cocoa-touch,uibutton,target-action,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]]; TaskButt

当按下我创建的按钮时,此代码导致“无效选择器”错误。
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
函数。将按钮的
目标设置为
self
是否意味着它应该在
TaskButtons
类中查找名为
test
的函数?

问题在于ARC过早释放实例化对象。所以要解决这个问题,我需要保留更长的时间

Main.h

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

@property (nonatomic, retain) TaskButtons *tB;

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

请包含无效选择器消息的文本。这将告诉您操作消息真正发送到哪个对象。我发现它试图在调用选择器之前过早释放我的实例化对象。如果我将TaskButtons.m导入Main.h和TaskButtons*tB;在界面中。然后通过@property(非原子,retain)TaskButtons*tB将其保留在属性中;我可以将实例化的类保留足够长的时间来调用选择器,而不会过早释放我的类。
测试
是一种方法,而不是函数。这可能是次要的,但UIControl选择器的形式是
@selector(method:)
,其中签名看起来像
-(void)method:(id)sender
。忽略参数可能会导致意外行为。
[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];

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