我在设置 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");
}
问题是当我单击按钮时,我收到以下错误消息:
[SecondViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x685c050
(lldb)
我假设问题是我只将一个 View 传递到 UIScrollView 中,并且无法访问 Controller 。
知道如何解决这个问题吗?
最佳答案
消息“消息发送到已释放的实例
”意味着当变量在viewDidLoad<结束时超出范围时,您的
然而它的 View (包含它的按钮)是。通向一个带有指向死对象的指针的活对象。因此你的崩溃。secondViewController
变量未被保留
由于您使用的是 ARC,最快(可能是 hackie)的方法是在 TestViewController
的 ivar 中创建 SecondViewController
。
@implementation TestViewController{
SecondViewController *secondViewController; // with ARC ivars are strong by default
}
然后将 viewDidLoad
中的行更改为:
secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
但我相信正确的方法(当然我不知道你的应用程序的具体情况)可能是使用:
- (void)addChildViewController:(UIViewController *)childController __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);
如果这是 iPhone/iPod touch 应用程序,请注意;苹果表示,对于这些设备,比例通常应该是一个 View Controller 与一个内容屏幕。再说一次,我不知道您的应用程序的具体情况,只是想提一下。
关于ios - 为什么这个对象在 ARC 下被过早释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9487856/