簡體   English   中英

將可編碼結構編碼為JSON后如何存儲數據

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

我有一個自定義Plant Objects數組。 Plant是可Codable 我使用JSONEncoder().encode()獲取以JSON編碼的array ,但是如何存儲此JSON以便在應用程序關閉后可以保存它? 我記得使用NSCoder我可以在應用程序關閉時對其進行編碼,並使用required convenience init? 解碼,但我在這里看不到類似的選擇。 這是我試圖保存[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)
    }

}

輔助擴展

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

如果要檢查包含數據的文件,請導航到由返回的網址

FileManager.documentDirectoryURL

試試jsonData.write(to:url)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM