我收到越来越多来自苹果的崩溃报告(全部在 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 类型(Date
和 Calendar
)时,不鼓励将基础类型与原生 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/