ios - UITableViewController 被初始化两次

标签 ios initialization automatic-ref-counting

我试图以 UINavigationController 的方式呈现一个带有 UITableViewController 的 Root View ,但当按下按钮呈现模态视图时,应用程序不断崩溃。

- (IBAction)flipToDefaultsViewController:(id)sender
{

    RootTableViewController *controller = [[RootTableViewController alloc] initWithNibName:@"RootTableViewController" bundle:nil];

    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:controller];
    nc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

    [self presentModalViewController:nc animated:YES];
}

应用程序崩溃并显示以下消息:

[RootTableViewController numberOfSectionsInTableView:]: message sent to deallocated instance 0x5677b5

当我加载 Instruments 进行进一步查看时,很明显创建了两个 UITableViewController 实例,一个是 UINavigationController 的所有者,另一个是由UIKit。 UIKit 创建的实例是被释放并导致崩溃的实例。

当我将初始化从 initWithNibName:bundle: 更改为 init 时,UITableViewController 加载正常(我的 .xib 文件与类)。

我的问题是为什么会发生这种情况?

UITableViewController 添加到 UINavigationController 时,您不应该以这种方式初始化它吗?到目前为止,我已经对文档进行了搜索,但没有任何乐趣。

使用带有 ARC 的 iOS 5,但目标部署是 4.0。

最佳答案

我还没有弄清楚为什么该对象被初始化两次,但是我确实检查了用于创建 .xib 文件的步骤,看起来复制从 Storyboard 到 Interface Builder 的 View 。事后看来,这是有道理的,但由于 View 复制时没有错误,并且其他一切看起来都不错,所以很容易完成。

others 似乎也遇到了类似的问题。与类似results .

通过使用 nib 文件 (⌘-N) 创建 UITableViewController 的完全干净的子类,并将代码从初始类复制到新类中,我能够使用上面的初始代码来分配/初始化我的模态视图。

顺便说一句,我在开篇文章中错误地提到使用 init 时正确加载 nib 文件。事实并非如此,事实上 UITableViewController apparently 不会发生这种行为。其中类名与 .xib 文件相同的其他类将尝试首先加载 .xib。

关于ios - UITableViewController 被初始化两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972892/

相关文章:

objective-c - Cocoa 类成员变量在函数调用内部分配 nil 除非强制初始化/加载

objective-c - ARC - __unsafe_unretained 的含义?

ios - 从详细信息转入后更新 TableView 数据

swift - 有一段代码涉及到Delegate Up,希望我理解正确

ios - 通过 CFStream 的 HTTP 请求

python - 重新定义子类的 __init__ 以采用不同的参数

python实例变量初始化

ios - 过度释放对象 iOS 应用程序崩溃

iphone - iOS 应用程序打开时刷新 View

ios - Swift 中的多色文本