麻烦在Swift 3中解压缩原始类型的NSData

时间:2016-11-01 06:52:11

标签: ios swift nsuserdefaults nsdata cloudkit

我正在尝试将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")
                            }
                    })
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

第一次保存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 ...
相关问题