首页 > 解决方案 > 带有 Core Data 的 SwiftUI:获取带有谓词崩溃的请求

问题描述

我已成功将 Core Data 添加到我的 SwiftUI 项目中。我需要按类型过滤结果。当我向获取请求添加谓词时,应用程序在包含获取请求的视图尝试加载时崩溃。

错误是线程 1:EXC_BAD_ACCESS (code=1, address=0x1)

 @Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Task.entity(),
    sortDescriptors:[
        NSSortDescriptor(keyPath: \Task.type, ascending: true),
        NSSortDescriptor(keyPath: \Task.totalScore, ascending: false),
    ],
        predicate: NSPredicate(format: "type == %@", Int16(1))) //this is the line that crashes the app
 var tasks: FetchedResults<Task>

如果我将 Int16(1) 更改为 Int16(0),应用程序不会崩溃,但列表中不会出现任何数据。

这是我使用核心数据编写的第一个应用程序,所以我需要帮助。

标签: core-dataswiftui

解决方案


感谢安德鲁建造者。他让我找到了正确的方向。使用需要 Int 的谓词的正确方法是:

predicate: NSPredicate(format: "type == %i", Int16(1)))

当我应该使用 %i 时,我使用了 %@。


推荐阅读