2012-02-28 54 views
1

我有一个问题,设定目标为一个UIButton:为什么此对象过早地在ARC下解除分配?

// 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 :]:消息 发送到释放实例0x685c050

(LLDB)

我假设问题是我只传入一个视图到UIScrollView,我无法访问控制器。

任何想法如何解决这个问题?

回答

2

消息“message sent to deallocated instance”是指当变量出去的范围在viewDidLoad 结束你的secondViewController变量没有被保留但它的视图,其中包含它的按钮,表示。通过指向死对象的指针引导到活动对象。因此你的崩溃。

由于您使用的是ARC,最快(可能是hackie)的方式是将SecondViewController设置为TestViewController

@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应用程序,请谨慎使用;苹果已经表示,这些设备的比例通常应该是一个视图控制器到一个内容屏幕。我不知道你的应用程序的具体细节,只是想提及它。

+0

谢谢NJones。第一个解决方案不起作用,但第二个解决方案是现货。 – jonnycage 2012-02-29 20:45:15

相关问题