ios - 在 Swift 中进行简单的 Date() 操作时崩溃

标签 ios iphone swift date date-manipulation

我收到越来越多来自苹果的崩溃报告(全部在 iPhone 5,iOS 10.3.3 上),代码行如下:

    let date = NSDate()
    var dateComponents = DateComponents()
    dateComponents.hour = -6
    let calculatedDate = NSCalendar.current.date(byAdding: dateComponents, to: date as Date)

    let selectStatement = "SELECT nr from info where date > \(UInt((calculatedDate!.timeIntervalSince1970)) * 1000);"

崩溃报告指出最后一行是问题行。看来,calculatedDate 没有实例化。

在以前的版本中,第一行甚至发生崩溃(iPhone 5,iOS 10.3.2)

我无法在 iPhone 6s 上重现这些崩溃。

对这些陈述中可能出现的问题有什么建议吗?

最佳答案

问题是 iPhone 5 是 32 位设备,您遇到整数溢出。查看错误 here当显式地将结果转换为 Int32 时。

如果您的 select 语句确实需要整数值,请使用 UInt64 而不是 UInt 来解决 32 位设备上的溢出问题。

与该问题无关,但是当您只能使用原生 Swift 类型(DateCalendar)时,不鼓励将基础类型与原生 Swift 类型混合使用。

明确显示问题的代码:

import Foundation

let date = Date()
var dateComponents = DateComponents()
dateComponents.hour = -6
let calculatedDate = Calendar.current.date(byAdding: dateComponents, to: date)
let selectStatement = "SELECT nr from info where date > \(UInt((calculatedDate!.timeIntervalSince1970)) * 1000);"
print(selectStatement) //prints 1504234558000
print(Int32(1504234558000))

ERROR at line 9, col 7: integer overflows when converted from 'Int' to 'Int32' print(Int32(1504234558000))

关于ios - 在 Swift 中进行简单的 Date() 操作时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45996436/

相关文章:

ios - 在 Xcode/Swift 中使用预设置 View

ios - 核心蓝牙 : What's the correct way of retrieving multiple disconnected peripherals?

swift - 在 macOS 上使用 Swift 3 从剪贴板读取

ios - UICollectionView 状态恢复 : customizing scroll position

ios - 如何更改设置为 UITextField inputView 的 UIDatePicker 的背景颜色?

ios - 在本地存储远程通知

iphone - 调试 init 中的内存泄漏

ios - 在tableview中删除一行

ios - 使用 UITableView 嵌入 UIScrollView

ios - 这一行代码在 Swift 2+ 中的等价物是什么