You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@SectionedFetchRequest与TimeInterval时类型转换崩溃求助

解决@SectionedFetchRequest崩溃:__NSTaggedDate无法转为NSNumber

核心原因

你遇到的崩溃是因为Core Data底层存储的标量Date类型实际是私有类__NSTaggedDate(Date的子类),但你指定的SectionedFetchResults泛型section类型是TimeInterval?——TimeInterval本质是Double,对应Core Data中的NSNumber类型,Date对象无法直接强转为NSNumber,因此触发类型转换错误。

解决方案

方案1:修正类型匹配(推荐)

直接把SectionedFetchResults的section类型改为Date?,和Core Data实际返回的类型对齐,后续需要TimeInterval时再做转换:

修改后的代码:

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

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

如果需要在界面中使用时间戳,可在遍历section时转换:

for section in itemsSections {
    if let sectionDate = section.id {
        let timestamp = sectionDate.timeIntervalSince1970
        // 在这里使用timestamp
    }
}

方案2:调整Core Data模型属性类型

如果必须用TimeInterval作为section标识,可修改Category实体的rawDate属性:

  1. 打开Core Data模型文件,将rawDate的类型从Date改为Double
  2. 更新实体类代码(确保rawDate类型为TimeInterval/Double)
  3. 若已有存储数据,需考虑数据迁移(可选择轻量迁移)

此时原代码的SectionedFetchResults<TimeInterval?, Item>就能正常运行,因为Core Data返回的是NSNumber类型,可直接转为TimeInterval。

内容的提问来源于stack exchange,提问作者Arnaud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:35:17