2017-09-01 31 views
0

操作我得到了更多來自蘋果(所有的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);" 

的crash-報告指出最後一行是問題線。所以看起來,calculateDate沒有實例化。

在以前版本的崩潰,甚至在第一線發生(iPhone 5,iOS版10.3.2)

我自己不能在iPhone 6S再現這些崩潰。

有什麼建議可能在這些陳述中出錯?

+0

當它們具有本機Swift等效項時,不要使用Foundation類型。使用「日期」和「日曆」。 –

+0

第一:你似乎在混合NSStuff('NSDate'和'Date',這導致了可以避免的劇組)和Swift Types。這不建議用於Swift 3代碼。 – Larme

+0

「我...不能在iPhone 6s上重現這些崩潰。」...在iPhone 5模擬器上執行它,並且很容易重現。請參閱下面的[David的回答](https://stackoverflow.com/a/45996612/1271826)。 – Rob

回答

1

問題是,iPhone 5是一個32位設備,你會得到一個整數溢出。將結果顯式轉換爲Int32時,請參閱錯誤here

使用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位於第9行,第7欄:從 'INT' 轉換爲 '的Int32' 打印時整數溢出(的Int32(1504234558000))

+1

解決問題,而你在寫作。在過去2小時內將整個項目更新爲(U)Int64。謝謝 – tartsigam

0

使用Date()而不是NSDate()& Calendar而不是NSCalendar。

let date = Date() 
var dateComponents = DateComponents() 
dateComponents.hour = -6 
if let calculatedDate = Calendar.current.date(byAdding: dateComponents, to: date) { 
    let selectStatement = "SELECT nr from info where date > \(UInt((calculatedDate.timeIntervalSince1970)) * 1000);" 
} 
+2

並使用'日曆'而不是'NSCalendar' ... –

+1

所有的優點,但與他的問題無關。 – Rob