带有核心数据的 SwiftUI:使用谓词崩溃获取请求

SwiftUI with Core Data: Fetch request with predicate crashes

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

错误是线程 1:EXC_BAD_ACCESS(代码=1,地址=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),应用程序不会崩溃,但列表中不会显示任何数据。

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

感谢 andrewbuilder。他让我朝正确的方向看。使用需要 Int 的谓词的正确方法是:

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

我本应使用 %i 却使用了 %@。

您还可以将 int 设为 NSNumber 对象:

NSPredicate(format: "type == %@", @(1))