0

我尝试将数组保存[String: Any]为用户默认值,并且在某些情况下它可以工作,但其他情况则不能。我使用以下内容保存为默认值:

 static func savingQueueToDisk(){
        let queueDict = App.delegate?.queue?.map({ (track) -> [String: Any] in
            return track.dict
        })

        if let queueDict = queueDict{
            UserDefaults.standard.set(queueDict, forKey: App.UserDefaultKey.queue)
            UserDefaults.standard.synchronize()
        }
    }

Queue是一个Track数组,定义如下:

class Track {

    var dict: [String: Any]!

    init(dict: [String: Any]) {
        self.dict = dict
    }

    var album: Album?{
        guard let albumDict = self.dict[AlbumKey] as? [String: Any] else{
            return nil
        }
        return Album(dict: albumDict)
    }

    var artists: [Artist]?{
        guard let artistsDict = self.dict[ArtistsKey] as? [[String: Any]] else{
            return nil
        }
        let artists = artistsDict.map { (artistdict) -> Artist in
            return Artist(dict: artistdict)
        }
        return artists
    }


    var id: String!{
        return self.dict[IdKey] as! String
    }


    var name: String?{
        return self.dict[NameKey] as? String
    }

    var uri: String?{
        return self.dict[URIKey] as? String
    }        
}

从同一个 API 检索时,我得到了不同的输出

崩溃输出: http ://www.jsoneditoronline.org/?id=cb45af75a79aff64995e01e5efc0e7b6

有效输出: http ://www.jsoneditoronline.org/?id=0939823a4ac261bd4cb088663c092b20

4

1 回答 1

0

事实证明,直接将数组存储到用户默认值是不安全的[String: Any],并且它可能会根据它包含的数据而中断,因此抱怨不能将 none-property-list 设置为用户默认值。我通过首先将数组转换[String: Any]Datausing 来解决这个问题JSONSerialization,现在它可以正确保存。

解决方案:

//saving current queue in the app delegate to disk
    static func savingQueueToDisk(){
        if let queue = App.delegate?.queue{
            let queueDict = queue.map({ (track) -> [String: Any] in
                return track.dict
            })
            
            if let data = try? JSONSerialization.data(withJSONObject: queueDict, options: []){
                UserDefaults.standard.set(data, forKey: App.UserDefaultKey.queue)
                UserDefaults.standard.synchronize()
            }else{
                print("data invalid")
            }
        }
    }
    
    //retriving queue form disk
    static func retrivingQueueFromDisk() -> [Track]?{
        if let queueData = UserDefaults.standard.value(forKey: App.UserDefaultKey.queue) as? Data{
            guard let jsonObject = try? JSONSerialization.jsonObject(with: queueData, options: []) else{
                return nil
            }
            
            guard let queueDicts = jsonObject as? [[String: Any]] else{
                return nil
            }
            let tracks = queueDicts.map({ (trackDict) -> Track in
                return Track(dict: trackDict)
            })
            return tracks
        }
        return nil
    }
于 2017-05-16T20:41:23.510 回答