简体   繁体   English

将可编码结构编码为JSON后如何存储数据

[英]How to Store Data once I've encoded Codable Struct to JSON

I have an array of custom Plant Objects . 我有一个自定义Plant Objects数组。 Plant is Codable . Plant是可Codable I use JSONEncoder().encode() to get the array encoded in JSON , but how do I store this JSON , so that it can be saved once the app closes? 我使用JSONEncoder().encode()获取以JSON编码的array ,但是如何存储此JSON以便在应用程序关闭后可以保存它? I remember with NSCoder I could just encode it when the app closes and use the required convenience init? 我记得使用NSCoder我可以在应用程序关闭时对其进行编码,并使用required convenience init? to decode it, but i don't see a similar option here. 解码,但我在这里看不到类似的选择。 Here is my Singleton Class in which I am trying to save the [Plant] 这是我试图保存[Plant] Singleton Class

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)
    }

}

Helper extensions.. 辅助扩展

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
        )
    }
}

Creating a folder that will contain your data file 创建一个包含您的数据文件的文件夹

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

Saving - 正在保存-

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

Decode - 解码-

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)
  }

If you want to check the file containing your data, navigate to the url returned by 如果要检查包含数据的文件,请导航到由返回的网址

FileManager.documentDirectoryURL

试试jsonData.write(to:url)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM