![](/img/trans.png)
[英]Example of Custom Class on the Transformable property of Core Data
[英]Core Data Custom Transformable Object Class Array
重要的
我了解到我在下面所做的並不是解決我的問題的最明智的方法。 我很想看到我的問題的解決方案,但現在我能夠通過使用 Core Data 一對多關系來實現我的目標,這很有效!
原帖
我有一個名為TestPeriods
的核心數據實體,我希望它有一個名為periods
的屬性,它是可轉換的,並且由一個名為PeriodClass
的自定義類的數組PeriodClass
總而言之,當我嘗試訪問保存在我的實體中的時間段時,出現了問題,正如您將在最后看到的那樣。
這是我的實體擴展
extension TestPeriods {
@nonobjc public class func fetchRequest() -> NSFetchRequest<TestPeriods> {
return NSFetchRequest<TestPeriods>(entityName: "TestPeriods")
}
@NSManaged public var periods: [PeriodClass]?
}
這是帶有開始、結束和句點的PeriodClass
public class PeriodClass: NSObject, NSCoding {
var start: Date?
var end: Date?
var period: Int16?
public func encode(with aCoder: NSCoder) {
aCoder.encode(start, forKey: "start")
aCoder.encode(end, forKey: "end")
aCoder.encode(period, forKey: "period")
}
public required init?(coder aDecoder: NSCoder) {
start = aDecoder.decodeObject(forKey: "start") as! Date
end = aDecoder.decodeObject(forKey: "end") as! Date
period = aDecoder.decodeObject(forKey: "period") as! Int16
}
init(start: Date, end: Date, period: Int16) {
super.init()
self.start = start
self.end = end
self.period = period
}
}
這是我保存到TestPeriods
實體的方式
let container = TestPeriods(context: PersistenceServce.context)
// The 'period' I refer to below is just an object with the same start, end, and period and I know is not nil
let x = PeriodClass(start: period.start!, end: period.end!, period: period.period)
container.periods?.append(x)
// Saving the object here
PersistenceServce.saveContext()
// I know this Persistence Service is not a problem as I use it for other Core Data Objects
問題是當我嘗試檢索PeriodClass
數組時
let tFetch: NSFetchRequest<TestPeriods> = TestPeriods.fetchRequest()
do {
let classes = try PersistenceServce.context.fetch(tFetch)
print("TEST CLASS COUNT \(classes.count)")
...
}
在這里,它打印1
因為我之前保存了一個具有多個周期的實體
然而,當我打電話
print("TEST CLASS PERIODS \(classes[0].periods)")
我得到的只是零
出於某種原因,它正在保存實體,但沒有正確保存應該與之相伴的時間段。 請讓我知道我做錯了什么以及如何解決這個問題。 謝謝!
看起來container.periods
為零,因此該行:
container.periods?.append(x)
什么也沒做。 您需要先將periods
初始化為一個空數組,然后才能向其追加項目。 或者對於第一個項目,只需創建一個包含該項目的數組:
container.periods = [x]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.