【发布时间】:2017-10-27 14:41:37
【问题描述】:
我有这些类型的课程:
import UIKit
class Report: Codable {
var name: String = ""
var budgetLines: [ReportLines] = []
init() {
self.name = "My Report"
self.budgetLines = [ReportLines(name: "Test1", parent: self), ReportLines(name: "Test2", parent: self), ReportLines(name: "Test3", parent: self)]
}
}
class ReportLines: Codable {
var name: String
weak var parent: Report?
init(name: String, parent: Report) {
self.name = name
self.parent = parent
}
}
let report = Report()
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let archiveURL = documentsDirectory.appendingPathComponent("Report").appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedReport = try? propertyListEncoder.encode(report)
try? encodedReport?.write(to: archiveURL, options: .noFileProtection)
重要细节:ReportLines 类包含一个指向所属 Report 类的指针。这个想法是可以编写如下代码:
myReportLine.parent!.name
当我尝试将其保存到 plist 中时,编码操作会挂起。我怀疑是这种情况,因为它试图编码一个对象,该对象包含一个包含指向外部对象的指针的对象数组。 Codable 可能会进入循环。
我怎样才能防止这种情况发生?
【问题讨论】:
-
你有一个循环依赖(父) - 这就是它导致循环的原因。只有手动编码实现才能解决这个问题。