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

如何使用sortDescriptors获取前一视图的CoreData用户输入数据

精准获取刚创建的CoreData闪卡数据方案

方案1:通过唯一UUID追踪(最可靠)

给FlashCardData实体新增一个uuid属性(类型设为String,勾选「Indexed」提升查询效率):

  1. 在TermDefinitionView创建新闪卡时,生成唯一UUID并赋值:
let newCard = FlashCardData(context: viewContext)
newCard.date = Date()
newCard.uuid = UUID().uuidString
// 其他属性赋值
try? viewContext.save()
  1. 跳转至SetView时,将这个uuid通过导航参数传递(比如用NavigationLink的tag+selection,或直接在目标视图初始化参数里接收)。
  2. 在SetView的@FetchRequest中使用精确匹配谓词:
@FetchRequest(
    sortDescriptors: [],
    predicate: NSPredicate(format: "uuid == %@", selectedUUID)
) var recentCards: FetchedResults<FlashCardData>

这种方式完全不受时间重复、多用户同时创建等场景影响,精准度最高。

方案2:优化时间范围谓词(适合无额外属性需求场景)

如果不想新增属性,可以在保存新闪卡时先记录精确的创建时间戳,再用这个时间做精准匹配:

  1. 保存前记录时间:
let creationDate = Date()
let newCard = FlashCardData(context: viewContext)
newCard.date = creationDate
// 其他属性赋值
try? viewContext.save()
  1. 跳转时传递creationDate,SetView中用谓词匹配:
// 考虑Date精度问题,用极小时间范围避免匹配偏差
let predicate = NSPredicate(format: "date >= %@ AND date <= %@", 
                            creationDate as CVarArg, 
                            creationDate.addingTimeInterval(0.1) as CVarArg)
@FetchRequest(
    sortDescriptors: [],
    predicate: predicate
) var recentCards: FetchedResults<FlashCardData>

注意:如果用户在极短时间内创建多个闪卡,该方案可能匹配到多条数据,仅适合单条创建场景。

方案3:直接传递创建好的对象(最直接)

不需要用@FetchRequest查询,直接把刚创建的FlashCardData对象传递给SetView:

  1. TermDefinitionView中保存后,通过导航参数传递对象:
NavigationLink(destination: SetView(selectedCard: newCard)) {
    Text("保存")
}
  1. SetView直接接收并展示:
struct SetView: View {
    let selectedCard: FlashCardData
    
    var body: some View {
        // 直接使用selectedCard的属性展示
        Text(selectedCard.term ?? "")
        Text(selectedCard.definition ?? "")
    }
}

这种方式跳过CoreData查询步骤,效率最高,适合仅展示单条新创建数据的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:00:59