ios - 为什么这个对象在 ARC 下被过早释放?

标签 ios uiscrollview uibutton automatic-ref-counting

我在设置 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<结束时超出范围时,您的secondViewController变量未被保留 然而它的 View (包含它的按钮)是。通向一个带有指向死对象的指针的活对象。因此你的崩溃。

由于您使用的是 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/

相关文章:

ios - 中心 ScrollView 对象到每个水平滚动页面 - Xamarin iOS

ios - 使用大数据源使 CPPickerView 滚动更快

swift - UIView block 动画完成始终为真

ios - 触摸一次后如何使 UIButton 不可点击并隐藏和取消隐藏按钮? - swift

ios - 禁用 tabBar 上的用户交互

ios - 有关如何从所需设备捕获 "attempt to insert nil object"的建议

objective-c - UITableView 像联系人应用程序编辑模式

iphone - CGImageGetBytesPerRow() 在 iOS 模拟器和 iOS 设备上返回不同的值

swift - 如何以编程方式单击按钮?

ios - NS无效参数异常 : App crashes upon opening