swift4 - 如何使用可编码和文件管理器在 swift 4 中保存数据

标签 swift4 codable

嗨,每个人都知道如何在 swift 4 中保存数据
我制作了一个表情符号应用程序,我可以描述表情符号,我有一个 future ,我可以在应用程序中保存新的表情符号

import Foundation

struct Emoji : Codable {
    var symbol : String
    var name : String
    var description : String
    var usage : String
    static let documentsdirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    static let archiveurl = documentsdirectory.appendingPathComponent("emojis").appendingPathExtension("plist")

    static func SaveToFile (emojis: [Emoji]) {
        let propetyencod = PropertyListEncoder()
        let encodemoj = try? propetyencod.encode(emojis)
        try? encodemoj?.write(to : archiveurl , options : .noFileProtection)
    }
    static func loadeFromFile () -> [Emoji] {
    let propetydicod = PropertyListDecoder()
        if let retrivdate = try? Data(contentsOf: archiveurl),
        let decodemoj = try?
            propetydicod.decode(Array<Emoji>.self, from: retrivdate){

        }
        return decodemoj        in this line i get error
    }

}

最佳答案

发生错误的原因是 decodemoj超出范围。你需要写

static func loadeFromFile() -> [Emoji] {
    let propetydicod = PropertyListDecoder()
    if let retrivdate = try? Data(contentsOf: archiveurl),
       let decodemoj = try? propetydicod.decode(Array<Emoji>.self, from: retrivdate) {
         return decodemoj
    }
    return [Emoji]()
}

并在出现错误时返回一个空数组。或者将返回值声明为可选数组并返回 nil .

但为什么不是 do - catch堵塞?
static func loadeFromFile() -> [Emoji] {
   let propetydicod = PropertyListDecoder()
   do {
      let retrivdate = try Data(contentsOf: archiveurl)
      return try propetydicod.decode([Emoji].self, from: retrivdate)
   } catch {
     print(error)
     return [Emoji]()
   }
}

关于swift4 - 如何使用可编码和文件管理器在 swift 4 中保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549793/

相关文章:

swift - 将状态保存在用户默认值中

ios - 解析 JSON iOS-Swift

swift 4 : With Codable `Generic parameter ' T' could not be inferred`

ios - 将[[((Int,String)]]]组合成[(Int,String)]的优雅方法?

swift - 约束 anchor 在 Swift 4 中工作不正常

json - 如何将图像数组从 json 格式解析为 TableView

Swift.DecodingError.Context

ios - 在 swift 4 中验证电话号码时,我从 firebase 收到 'invalid token'

json - 使用可编码的值,有时是 Int,有时是 String

ios - UIImageJPEGRepresentation 已被实例方法 UIImage.jpegData(compressionQuality :)