Search code examples
objective-cioscocoa-touchuibuttontarget-action

Button's action causes "invalid selector" crash -- why?


This code results in an "invalid selector" error when the button I create is pressed. Where is the test function fetched from?

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

It seems that the test function isn't being called. Doesn't setting the button's target to self here mean it should look in the TaskButtons class for the function called test?


Solution

  • The problem is ARC is releasing the instantiated object too soon. So to solve this I would need to retain it longer.

    Main.h

    #import "TaskButtons.m"
    @interface ViewController : UIViewController {
         TaskButtons *tB;
    }
    
    @property (nonatomic, retain) TaskButtons *tB;