我正在尝试在我的添加中添加一个颜色选择器,我使用这个 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 方法会被无限调用
----更新-----
最佳答案
与 Objective-C 中一样,类可以具有方便的(辅助)初始值设定项和指定的(主)初始值设定项。
代码执行路径应该是:
- 便利初始化程序应使用
self.designatedInit()
调用指定初始化程序。 - 指定初始值设定项应使用
super.designatedInit()
调用 super 的指定初始值设定项。
在您的代码中,init()
是一个便利初始化程序 (convenience init()
)。调用 self.init() 会导致无限循环,因为正如 Dan 所说,这是实际运行的函数本身。
如果将其更改为 super.init()
,则便利初始化程序正在调用 super 的初始化程序,由于上述规则 #1,这是非法的。
要做什么?
- 检查
init()
是否确实是一个方便的初始化程序。 - 如果是这样,请调用
self.designatedInit()
而不是self.init()
。 - 如果不是这样,请更改
init()
的分类并调用super.init()
(或任何父类(super class)的指定初始值设定项。
关于ios - 在 Objective C 项目中初始化 swift 类会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084877/