ios - 由于 TableView Controller 初始化,应用程序崩溃

标签 ios objective-c swift

我初始化 tableView 的代码是:

convenience override init(style: UITableViewStyle) {
    self.init(style: .Grouped)
    // Custom initialization
    self.title = NSLocalizedString("mdm.agent.common.desktopCentral", comment : "")
}

错误是行上的EXC_BAD_ACCESS

 self.init(style: .Grouped)

为什么这种类型的初始化会引发错误,但适用于 objective-c ? Objective-C 代码是:

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
    // Custom initialization

    self.title = NSLocalizedString(@"mdm.agent.common.desktopCentral", nil);
}
return self;

最佳答案

您需要在构造函数中调用父类(super class)的 init 方法,或者在您自己的类中调用指定的初始化程序。

在您发布的示例 Objective-C 代码中有一行

self = [super initWithStyle:UITableViewStyleGrouped];

这一行调用了 initWithStyle: 的父类(super class)实现。

在您的代码中,您从导致无限递归的同一方法中调用 self.init(style: .Grouped)。您可以通过两种不同的方式解决此问题,要么调用不同的指定初始化程序,例如 self.init(),要么删除 convenience 关键字以使其成为指定初始化程序,这将让您调用父类(super class)实现。

你可能想做第二个选项,它看起来像这样:

override init(style tableStyle: UITableViewStyle) {
    super.init(style: style) //use the style value passed into the method
    // Custom initialization
    self.title = NSLocalizedString("mdm.agent.common.desktopCentral", comment : "")
}

关于ios - 由于 TableView Controller 初始化,应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198776/

相关文章:

ios - Swift/Watchkit 中涉及字符串的函数问题

设置 setVisibleXRangeMaximum 时,iOS-Charts X 轴值无限重复

ios - 从核心数据中的一对多关系中删除对象

iphone - 消除模态视图层次结构——一个优雅的解决方案

ios - 更改 UITextField 宽度?

ios - 如何检测Touch ID可用但未配置

ios - TableView 中的不同长度单元格在滚动 Swift 时使 View 对齐

ios - 在字典 Swift iOS 中过滤字典数组中的 json 响应

iphone - 停止闲置一段时间后,IOS音频将无法工作

ios - SceneDelegate 中的 UIWindow