gpt4 book ai didi

json - NSCoding 和 Codable 属性 <=> JSON 格式 <=>(读/写)文件

转载 作者:行者123 更新时间:2023-11-28 05:54:17 24 4
gpt4 key购买 nike

我需要从/向 JSON 格式的文件读取/写入 Codable(例如,Date)和 NSCoding(例如,NSMutableAttributedString)属性。在研究了如何使用 Codable 读取和写入文件、如何以 JSON 格式执行此操作以及当某些属性不符合 Codable(但确实符合 NSCoding)时如何将 NSCoding 与 Codable 结合之后,我拼凑在一起以下代码并在此过程中使自己感到困惑。

我终于想出了如何测试它,并相应地进行了更改。但我仍然想知道这三种解码器/编码器类型(NSCoding、Codable 和 JSON)如何相互作用或相互替代。

import Foundation

class Content: Codable {

// Content
var attrStr = NSMutableAttributedString(string: "")
var date: Date?

// Initializer for content
init(attrStr: NSMutableAttributedString, date: Date) {
self.attrStr = attrStr
self.date = date
}

// Need to explicitly define because NSMutableAttributedString isn't codable
enum CodingKeys: String, CodingKey {

case attrStr
case date
}

// Need to explicitly define the decoder. . . .
required init(from decoder: Decoder) throws {

let container = try decoder.container(keyedBy: CodingKeys.self)

date = try container.decode(Date.self, forKey: .date)

let attrStrData = try container.decode(Data.self, forKey: .attrStr)
attrStr = NSKeyedUnarchiver.unarchiveObject(with: attrStrData) as? NSMutableAttributedString ?? NSMutableAttributedString(string: "Error!")
}

// Need to explicitly define the encoder. . . .
func encode(to encoder: Encoder) throws {

var container = encoder.container(keyedBy: CodingKeys.self)

try container.encode(date, forKey: .date)

let attrStrData = NSKeyedArchiver.archivedData(withRootObject: attrStr)
try container.encode(attrStrData, forKey: .attrStr)
}

static func getFileURL() -> URL {

// Get the directory for the file
let docsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// Get the full path and filename
return docsDir.appendingPathComponent("contentArray").appendingPathExtension("cntnt")
}

static func saveToFile(content: [Content]) {

// Get the file's URL
let fileURL = getFileURL()

do {
// Encode the data
let data = try JSONEncoder().encode(content)
// Write to a/the file
try data.write(to: fileURL)

} catch {
print("Could not encode or save to the file!")
}
}

static func loadFromFile() -> [Content] {

// Get the file's URL
let fileURL = getFileURL()

do {
// Read from the file
let data = try Data(contentsOf: fileURL)
// Decode the data
return try JSONDecoder().decode([Content].self, from: data)

} catch {
print("Could not decode or read from the file!")
return []
}
}
}

最佳答案

About your alternative, I wouldn't know how to do that.

我尝试为 NSMutableAttributedString 实现 Codable。我不得不嵌入而不是子类化它,因为它是一个类簇。 Source

class MutableAttributedStringContainer: Codable {
let attributedString: NSMutableAttributedString

init(attributedString: NSMutableAttributedString) {
self.attributedString = attributedString
}

public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let data = try container.decode(Data.self)

let archiver = try NSKeyedUnarchiver(forReadingFrom: data)
attributedString = NSMutableAttributedString(coder: archiver)!
}

public func encode(to encoder: Encoder) throws {
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
attributedString.encode(with: archiver)

var container = encoder.singleValueContainer()
try container.encode(archiver.encodedData)
}
}

这是一个如何使用它的例子。

func testing() {
let attributedString = NSMutableAttributedString(string: "Hello world!")
let attributedStringContainer = MutableAttributedStringContainer(attributedString: attributedString)

// Necessary because encoding into a singleValueContainer() creates a
// JSON fragment instead of a JSON dictionary that `JSONEncoder` wants
// create.
struct Welcome: Codable {
var attributedString: MutableAttributedStringContainer
}
let welcome = Welcome(attributedString: attributedStringContainer)

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(welcome)
print(String(bytes: data, encoding: .utf8) as Any)

let decoder = JSONDecoder()
let welcome2 = try! decoder.decode(Welcome.self, from: data)
print("decoded to string:", welcome2.attributedString.attributedString.string)
}

But it also looks wrong. For example, the explicitly defined decoder and encoder seem disconnected from the JSONDecoder and -Encoder.

Codable 结构相互构建。如果所有底层结构都实现了Codable,编译器就可以自己创建编码和解码函数。如果没有,开发人员必须对它们进行编码并将它们放在 CodingKey 上,解码时也是如此。

例如,可以以任何方式将它们转换为数据,然后将它们作为数据编码到 CodingKey。也许读一个Raywenderlich TutorialCodable 上更好地理解它。

There should be a discernible processing stream, but I can't see how the three kinds of decoders/encoders interact or substitute for one another.

有支持特定编码器/解码器对的解码器/编码器和方法。

NSCodingNSKeyedUnarchiver/NSKeyedArchiver 一起工作并返回 NSData 这只是数据,虽然不是人类可读的形式。

Codable 与任何支持 Codable 的编码器/解码器对一起工作,更具体地说,在我们的例子中是 JSONEncoder/JSONDecoder,它返回 Data 是人类可读的格式JSON,可以打印,因为这里的数据是用.utf8编码的。

关于json - NSCoding 和 Codable 属性 <=> JSON 格式 <=>(读/写)文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com