ios - 将 Codable 结构编码为 JSON 后如何存储数据

标签 ios arrays json swift xcode

我有一组自定义植物对象PlantCodable。我使用 JSONEncoder().encode() 获取以 JSON 编码的 array,但如何存储此 JSON,以便在应用程序关闭后可以保存?我记得使用 NSCoder 我可以在应用程序关闭时对其进行编码并使用 required convenience init? 对其进行解码,但我在这里没有看到类似的选项。这是我的 Singleton Class,我试图在其中保存 [Plant]

import Foundation
public class Singleton{
    static let sInstance = Singleton(mPL: [Plant]())
    var myPlantList: [Plant]

    init(mPL: [Plant]){
        self.myPlantList = mPL
    }

    public func savePlants(){
        let jsonData = try? JSONEncoder().encode(myPlantList)
    }

}

最佳答案

辅助扩展..

import Foundation

public extension FileManager {
// Returns a URL that points to the document folder of this project.
    static var documentDirectoryURL: URL {
        return try! FileManager.default.url(
            for: .documentDirectory,
            in: .userDomainMask,
            appropriateFor: nil,
            create: false
        )
    }
}

创建一个将包含您的数据文件的文件夹

let documentSubdirectoryURL = URL(
    fileURLWithPath: "MyFolder",
    relativeTo: FileManager.documentDirectoryURL
)
try? FileManager.default.createDirectory(
    at: documentSubdirectoryURL,
    withIntermediateDirectories: false
)

保存-

do {
     let yourURL = URL(fileURLWithPath: "yourFileName", relativeTo: FileManager.documentDirectoryURL.appendingPathComponent("MyFolder")).appendingPathExtension("swift")
    ///ENCODE...
    try jsonData.write(to: yourURL)
}

解码-

do {
    let yourURL = URL(fileURLWithPath: "yourFileName", relativeTo: FileManager.documentDirectoryURL.appendingPathComponent("MyFolder")).appendingPathExtension("swift")
    let jsonDecoder = JSONDecoder()
    let data = try Data.init(contentsOf: yourURL)
    let value = try jsonDecoder.decode([Plant].self, from: data)
  }

如果你想检查包含你的数据的文件,导航到返回的 url

FileManager.documentDirectoryURL

关于ios - 将 Codable 结构编码为 JSON 后如何存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50169199/

相关文章:

javascript - 循环遍历对象中的多个数组以在新数组中创建多个对象?

javascript - 动态替换数组中的值

java - 返回数组中整数的第一个数字

ios - XCTest typeText无法将键盘切换到另一种语言

ios - BarButtonItem 未显示

ios - 清晰的NSRunLoop流程

ios - 带有参数 iOS 的单例

javascript - 如何使用名为 "@attributes"的对象读取 JSON 输出?

json - 在不破坏 JSON 格式的情况下更新 JSON 文件

json 和类型转换