【问题标题】:Why this code crashes on iPhone 5?为什么这段代码在 iPhone 5 上崩溃?
【发布时间】:2017-02-09 09:43:09
【问题描述】:

以下代码:

func getCurrentMillis() -> Int64 {
    return Int64(Date().timeIntervalSince1970 * 1000)
}

在 [32 位] iPhone 5 上崩溃并显示消息:

EXC_BREAKPOINT (code=EXC_ARM_BREAKPOINT, subcode=0xe7ffdefe)

我不明白为什么这个计算的结果应该适合Int64,还是我遗漏了什么?

Stacktrace 显示了这一点(TextProcessor.textDidChange() 调用 getCurrentMillis()):

应OOPer的要求,我添加了TextProcessor的相关代码:

var timeOfLastInput: Int64 = 0

...

if getCurrentMillis() - timeOfLastInput > 150 {
    textMap.cursorPosition = nil
}

更新: 我已向 Apple 发送错误报告。

【问题讨论】:

  • 如果你知道Int64在32位设备上可用,为什么不显示TextProcessor.textDidChange()的代码。我可以向您保证,您的 getCurrentMillis() 在 32 位设备上运行良好。问题在于调用方。
  • Int64 在 32 位系统上可用。问题一定出在其他地方。
  • 您确定崩溃是在 getCurrentMillis 函数中吗?我无法从堆栈回溯中看到。
  • @Martin R top of stacktrace 没有提到它,但似乎它崩溃了因为它,即当我将Int64 更改为TimeInterval 时它工作正常。
  • timeOfLastInput的类型是什么?

标签: ios iphone swift crash 32-bit


【解决方案1】:

我不确定 Swift 编译器中发生了什么,但是当您编写时:

if getCurrentMillis() - timeOfLastInput > 150 {

Swift 在许多重载的减法运算符中使用了这个:

public func -<T : Strideable>(lhs: T, rhs: T) -> T.Stride

(使用 Xcode 8.2.1 测试。)

很遗憾,Int64.StrideInt,所以在 32 位系统中,当 timeOfLastInput0 时,运算结果会溢出。

要解决 Swift 的这种行为,您可以将行更改为:

if getCurrentMillis() > timeOfLastInput + 150 {

无论如何,您最好发送bug report to Appleto swift.org

【讨论】:

  • 好收获!在此处观察到类似的问题:stackoverflow.com/questions/27496415/swift-type-conversions.
  • 我认为if getCurrentMillis() - timeOfLastInput &gt; Int64(150) 也可以。 – 但无论如何,这种行为并不直观,并且违背了 Swift 声称的“安全性”。
  • 我很好奇,哪里说Int64.StrideInt
  • @SerhiiYakovenko,检查Strideable的定义。它的关联类型Stride 是从distance(to:)advanced(by:) 的定义中推断出来的。对于Int64,它们在SignedInteger 的扩展中定义为public func distance(to other: Self) -&gt; Intpublic func advanced(by n: Int) -&gt; Self
【解决方案2】:

您已经知道您的 iphone 5 在 32 位系统上运行。您想使用 64 位编码的 Int。其实是比不上的。您的 iPhone 无法存储它。

扩展 the_dahiya_boy 的解决方案:Int 大小在 32 位系统上与 Int32 相同,在 64 位系统上与 Int64 大小相同。

Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多