1
我在生產中有一個應用程序我試圖從Swift 2.2轉換爲Swift 3.我已經在XCode 8.1和XCode 8.2中試過了Swift 3代碼。NSKeyedArchiver不持久數據Swift 3
以下夫特2代碼完美地工作:
func saveItemsToCache() {
NSKeyedArchiver.archiveRootObject(items, toFile: itemsCachePath)
}
func loadItemsFromCache() {
if let cachedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(itemsCachePath) as? [TruckItem] {
items = cachedItems
}
}
var itemsCachePath: String {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent("Trucks.dat")
return fileURL.path!
}
但是當我使用轉換爲夫特3相同的代碼的數據沒有被持久:
func saveItemsToCache() {
print("SAVED TRUCKS:", items)
NSKeyedArchiver.archiveRootObject(items, toFile: itemsCachePath)
}
func loadItemsFromCache() {
if let cachedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemsCachePath) as? [TruckItem] {
items = cachedItems
print("LOADED TRUCKS:", items)
}
}
var itemsCachePath: String {
let documentsURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("Trucks.dat")
return fileURL.path
}
例控制檯輸出:
SAVED TRUCKS: [<TruckTelematics.TruckItem: 0xc852380>, <TruckTelematics.TruckItem: 0x9b23ba0>]
LOADED TRUCKS: []