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



我已经成功地将核心数据添加到我的 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))

最新更新