5

在我的应用程序中,我有两个视图控制器。第一个 Viewcontroller 是应用程序窗口的 rootViewController。当单击第一个 ViewController 中的按钮时,我将第二个 ViewController 的视图作为子视图添加到第一个视图中,第二个 ViewController 的视图中有一个按钮,我的问题是当我点击该按钮时应用程序崩溃

-(void)theCheckoutViewisExpandedwitPatient:(id)patient
{
    SecondViewController *sample=[[SecondViewController alloc]init];
    CGRect rect=sample.view.frame;
    rect.origin.y=30;
    rect.origin.x=305;
    [sample.view setFrame:rect];
    [self.view addSubview:[sample view]];
}
4

2 回答 2

4

The issue is that SecondViewController is not assigned to strong variable / property, therefore it is deallocated when the method returns.

Any variable pointing to an object, inside a method (called automatic variable if I remember correctly), will be removed from the memory when the method returns. As a result, object pointed to by that variable will be released. If this object is not retained anywhere else, by for example assigning to a strong property or strong instance variable, it will be deallocated. Now, what you are doing is, you grab second view controller's view and stick it into view hierarchy of the view controller's view where this method is defined. The method returns, variable is popped off the stack, SampleViewController is not retained in any way, so it gets released. Any actions that "new" view performs, that result in a call to its view controller (the second view controller), such as button tap event notification, will end up in a crash, as that view controller is no longer in the memory.

Btw. You are simply not doing it right. Look at View Controller Containment API, if you wanna write custom containers.

于 2013-05-17T14:11:54.907 回答
3

是的,问题就在这里。当您单击按钮时,它会尝试触发secondviewcontroller. get dealloc但是在您调用之前,secondviewcontroller 将在此方法调用之后超出范围( ) theCheckoutViewisExpandedwitPatient

我们可以简单地说[button->target not alive]

于 2013-05-17T13:59:33.723 回答