在 Swift 3 中以原始类型取消存档 NSData 时遇到问题

Trouble Unarchiving NSData in original type in Swift 3

我正在尝试将 CKRecordID 保存到 NSUserDefaults。检索时如何将其恢复为 CKRecordID 而不是 NSData 的原始类型?你能以这种方式使用 NSKeyArchiver 还是有其他方法?

func getRecordToUpdate(_ locations:CLLocation)
    {
        if defaults1.object(forKey: "locationData") == nil{
            locationRecord.setObject(locations, forKey: "location")
            let id = locationRecord.recordID
            let dataId = NSKeyedArchiver.archivedData(withRootObject: id)
            defaults1.set(dataId, forKey: "locationData")
            self.updateLocationRecord(locations: locations)
        }else{
            if let loadedData = defaults1.object(forKey: "locationData") {
                if (NSKeyedUnarchiver.unarchiveObject(with: loadedData as! Data)) != nil
                {
                    let publicDB = CKContainer.default().publicCloudDatabase
                    let lit = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData as! CKRecordID)
                    publicDB.fetch(withRecordID: lit ,completionHandler: {
                        (record, error) in
                        if error == nil
                        {
                            publicDB.delete(withRecordID: (record?.recordID)!, completionHandler: {
                                (record, error) in
                                if(error == nil){
                                    print("old record delete")
                                    let id = self.locationRecord.recordID.recordName
                                    self.locationRecord.setObject(locations, forKey: "location")
                                    self.defaults1.set(id, forKey: "locationData")
                                    self.updateLocationRecord(locations: locations)
                                }
                                else{
                                }
                            })
                        }else{
                            print("Error fetching previous record")
                            }
                    })
                }
            }
        }
    }

在您第一次保存 recordID 之后,它保证是 Data 代表一个 CKRecordID 对象。

从用户默认值中读取原始数据并将数据解档到记录id。

if let loadedData = defaults1.object(forKey: "locationData") as? Data {
   let lit = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as! CKRecordID
   let publicDB = CKContainer.default().publicCloudDatabase
   publicDB.fetch ...