I am having a problem setting the target for a UIButton:
// TestViewController.m
@implementation TestViewController
@synthesize scrollContentView
- (void)viewDidLoad
{
[super viewDidLoad];
SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
[self.scrollContentView addSubview:secondViewController.view];
}
@end
// SecondViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 addTarget:self action:@selector(button1Click:) forControlEvents:UIControlEventTouchUpInside];
button1.frame = CGRectMake(20, 45, 280, 40);
[self.view addSubview:button1];
}
- (IBAction)button1Click:(id)sender
{
NSLog(@"test");
}
The issue is when I click on the button I get the following error message:
[SecondViewController performSelector:withObject:withObject:]: message
sent to deallocated instance 0x685c050(lldb)
I am assuming that the issue is I am passing just a view into the UIScrollView and I cannot access the controller.
Any idea how to solve this?
The message “
message sent to deallocated instance” means that yoursecondViewControllervariable was not retained when the variable went out of scope at the end ofviewDidLoadhowever it’s view, which contains it’s button, was. Leading to a live object with a pointer to a dead object. Thus your crash.
Since you’re using ARC, the quickest (possibly hackie) way would be to make the
SecondViewControllerin ivar ofTestViewController.And then change the line in
viewDidLoadto:But I believe that the correct way (of course I don’t know the specifics of your app) would probably be to use:
A word of caution if this is an iPhone/iPod touch app; Apple has said for these devices the ratio should generally be one view controller to one screen of content. Again I don’t know the specifics of your app, just wanted to mention it.