应用程序在解除presentModalViewController后崩溃

时间:2011-07-30 19:57:34

标签: iphone ios4 crash

使用以下按钮转到另一个控制器时遇到问题

-(IBAction)art:(id)sender{

TestYourInfoViewController *test = [[TestYourInfoViewController alloc]
                              initWithNibName:@"TestYourInfoViewController" bundle:[NSBundle mainBundle]];
test.questionType = @"art";
testYourInfoViewC = test;
[testYourInfoViewC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self.navigationController presentModalViewController:testYourInfoViewC animated:YES ];
[test release];

}

当我回到以下

-(IBAction)back:(id)sender{
   [[self parentViewController] dismissModalViewControllerAnimated:YES];    

}

它使应用程序崩溃而没有堆栈跟踪..请问有什么问题。

1 个答案:

答案 0 :(得分:0)

标题中是否testYourInfoViewC定义为保留@property?如果是这样,您应该始终使用self和点符号来引用它。

- (IBAction)art:(id)sender
{
    TestYourInfoViewController *test = [[TestYourInfoViewController alloc]
                              initWithNibName:@"TestYourInfoViewController" bundle:[NSBundle mainBundle]];
    test.questionType = @"art";
    self.testYourInfoViewC = test;
    [self.testYourInfoViewC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self.navigationController presentModalViewController:self.testYourInfoViewC animated:YES ];
    [test release];
}

当你创建一个保留的@property@synthesize时,会创建一个setter来处理保留新对象和释放旧对象所涉及的内存管理,但是通过分配testtestYourInfoViewC你绕过那个合成的二传手。

让我们在这里逐步完成。您已使用test创建了alloc/init,因此将其retainCount设置为1.接下来,您已将testYourInfoViewC分配给test。保留计数没有变化,testYourInfoViewC现在只是指向与test相同的对象,而不是为自己保留副本。

现在,当您在release上调用test时,保留计数将返回0并且对象已取消分配。您TestYourInfoViewController的实例已完全消失,testYourInfoViewC现在正在风中飘扬。在尝试关闭它时,parentViewController将尝试在幕后向该对象发送一些消息,例如-viewWillDisappear:-viewDidDisappear:等。

编辑:以下是我在项目中处理此类情况的方法。我覆盖属性的getter并确定是否需要创建它。这样我就可以在我的代码中的任何地方调用该属性,我可以放心,如果它没有创建,它将被及时分配,初始化和设置。

- (TestYourInfoViewController *)testYourInfoViewC
{
    if (!testYourInfoViewC)
    {
        testYourInfoViewC = [[TestYourInfoViewController alloc] init]; // This will work because the .xib and class name are identical. 
        [testYourInfoViewC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    }

    return testYourInfoViewC;
}

在设置getter以提供延迟实例化后,您的-art:方法将如下所示......

- (IBAction)art:(id)sender
{
    [self.navigationController presentModalViewController:self.testYourInfoViewC animated:YES];
}