ios - 在 Objective C 项目中初始化 swift 类会导致无限循环

标签 ios objective-c swift

我正在尝试在我的添加中添加一个颜色选择器,我使用这个 https://github.com/gizmosachin/ColorSlider库仅用 swift 编写,我使用 Objective-C。我已遵循本指南 How to call Objective-C code from Swift关于如何在 Objective-C 项目中添加 Swift 库。我 99% 确定我已经正确配置了 xcode,因为我可以导入 swift 库并运行我的应用程序而不会出现错误,只有当我尝试实例化 swift 类时,应用程序才会崩溃,并且我看到swift 类被无限调用。该库的源代码是一个文件,列出以供引用,以防万一 ( https://github.com/gizmosachin/ColorSlider/blob/master/Source/ColorSlider.swift )

这是一个 init 方法(其他 init 被覆盖)

// MARK: Initializers
convenience init() {
    println("hi there swift")
    self.init()
    backgroundColor = UIColor.clearColor()
}

在我的日志中,我多次看到“hi There swift”打印出来。这就是我启动 swift 类(class)的方式

ColorSlider *colorSlider = [[ColorSlider alloc] init];

我知道包含上面代码行的函数只被调用一次,因为我使用 NSLog(@"output") 来查看它出现了多少次,输出如下所示

output
hi there swift
hi there swift
hi there swift
hi there swift
hi there swift
etc...to infinity or until app crashes

我是否正确实例化了 swift 类?我不知道为什么 swift 类的 init 方法会被无限调用

----更新-----

看起来下面的init方法也使用了super.init? enter image description here

最佳答案

与 Objective-C 中一样,类可以具有方便的(辅助)初始值设定项和指定的(主)初始值设定项。

代码执行路径应该是:

  1. 便利初始化程序应使用 self.designatedInit() 调用指定初始化程序。
  2. 指定初始值设定项应使用 super.designatedInit() 调用 super 的指定初始值设定项。

在您的代码中,init() 是一个便利初始化程序 (convenience init())。调用 self.init() 会导致无限循环,因为正如 Dan 所说,这是实际运行的函数本身。

如果将其更改为 super.init(),则便利初始化程序正在调用 super 的初始化程序,由于上述规则 #1,这是非法的。

要做什么?

  1. 检查 init() 是否确实是一个方便的初始化程序。
  2. 如果是这样,请调用 self.designatedInit() 而不是 self.init()
  3. 如果不是这样,请更改 init() 的分类并调用 super.init() (或任何父类(super class)的指定初始值设定项。

关于ios - 在 Objective C 项目中初始化 swift 类会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084877/

相关文章:

ios - backtrace 错过导致崩溃的函数

ios - 按钮的 UIScrollView - TouchUpInside?

swift - 为什么我需要在 UITableView 中的单元格上点击两次才能显示警报

swift - Swift 中的 "@exported"属性是什么

ios - 如何关闭ModalViewControllerAnimated : YES

ios - 为什么在设备旋转的纵向模式下不专门调用 UICollectionViewDelegateFlowLayout 方法?

ios - Xcode 6.3 的 NSParameterAssert 编译错误

objective-c - 为什么 C 标准提供未确定大小的类型(int、long long、char 与 int32_t、int64_t、uint8_t 等)?

ios - 从 xcode 中的 mainBundle 获取子目录

ios - 如何在出现之前访问将要出现的单元格?