【问题标题】:How to Store Data once I've encoded Codable Struct to JSON将 Codable Struct 编码为 JSON 后如何存储数据
【发布时间】:2018-05-04 07:11:25
【问题描述】:

我有一组自定义Plant ObjectsPlantCodable。我使用JSONEncoder().encode() 来获取array 编码为JSON,但是如何存储这个JSON,以便在应用程序关闭后可以保存它?我记得使用NSCoder 我可以在应用程序关闭时对其进行编码并使用required convenience init? 对其进行解码,但我在这里看不到类似的选项。这是我的单例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)
    }

}

【问题讨论】:

  • 您想存储植物对象数组吗?你可以使用 UserDefaults 来做同样的事情

标签: ios arrays json swift xcode


【解决方案1】:

助手扩展..

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

【讨论】:

  • 我已经在操场上检查了这一点,在此处打开FileManager.documentDirectoryURL 返回的 url 时,我可以检查存储数据的文件。
【解决方案2】:

试试 jsonData.write(to: url)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 2020-07-14
    • 2012-02-08
    • 1970-01-01
    • 2014-10-19
    • 2022-08-12
    • 1970-01-01
    • 2018-10-31
    相关资源
    最近更新 更多