2016-12-15 32 views
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: [] 

回答

0

我最近發現這個問題根本不在NSKeyedArchiver中,但是instea d在我的NSObject子類TruckItem中使用convenience init?(coder aDecoder: NSCoder)方法。

在雨燕2.2,你會喜歡這個解碼不同對象的屬性:

let IMEI = aDecoder.decodeObject(forKey: CodingKeys.IMEI) as! String 
let active = aDecoder.decodeObject(forKey: CodingKeys.active) as! Bool 
let daysInactive = aDecoder.decodeObject(forKey: CodingKeys.daysInactive) as! Int 

在斯威夫特3,而不是使用decodeObject()所有物業類型,看來現在有一些新的功能,以做到心中有數。以下是雨燕3解碼同一個對象的屬性:

let IMEI = aDecoder.decodeObject(forKey: CodingKeys.IMEI) as! String 
let active = aDecoder.decodeBool(forKey: CodingKeys.active) 
let daysInactive = aDecoder.decodeInteger(forKey: CodingKeys.daysInactive) 

花了相當長的一段時間,我發現這一點,希望這個答案可以節省從類似挫折的其他用戶。