@SectionedFetchRequest and TimeInterval: Could not cast value of type '__NSTaggedDate' to 'NSNumber'

53 Views Asked by At

This SectionedFetchRequest crashes with Could not cast value of type '__NSTaggedDate' to 'NSNumber'

@SectionedFetchRequest
private var itemsSections: SectionedFetchResults<TimeInterval?, Item>

internal init() {
    _itemsSections = SectionedFetchRequest(
        sectionIdentifier: \.category?.rawDate,
        sortDescriptors: [
            SortDescriptor(\.category?.rawDate, order: .forward)
        ],
        predicate: nil
    )
}

Item belongs to a Category which has a rawDate attribute. This attribute is a TimeInterval (non-optional/scalar Date).

Core Data has the requirement that the sort key must be stored in the database, so I can't use a computed property.

NSTaggedDate is a private type, and casting to Double?, NSNumber?, NSDate? or Date? doesn't work either.

How should I handle this?

PS: I'm declaring the SFR in the init because I anticipate that I'll add parameters to the View's init and use them in the predicate (currently nil).

1

There are 1 best solutions below

0
Arnaud On

I found a solution using computed variables.

In my Category:

@objc
var date: Date {
    get {
        return Date(timeIntervalSinceReferenceDate: self.rawDate)
    }
    set {
        self.rawDate = newValue.timeIntervalSinceReferenceDate
    }
}

And the new code

@SectionedFetchRequest
private var itemsSections: SectionedFetchResults<Date?, Item>

internal init() {
    _itemsSections = SectionedFetchRequest(
        sectionIdentifier: \.category?.date,
        sortDescriptors: [
            SortDescriptor(\.category?.rawDate, order: .forward)
        ],
        predicate: nil
    )
}