2016-12-15 52 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) 

花了相当长的一段时间,我发现这一点,希望这个答案可以节省从类似挫折的其他用户。