【问题标题】:SwiftUI with Core Data: Fetch request with predicate crashes带有 Core Data 的 SwiftUI:获取带有谓词崩溃的请求
【发布时间】:2020-01-04 14:30:46
【问题描述】:

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

错误是线程 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),应用不会崩溃,但列表中不会出现任何数据。

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

【问题讨论】:

  • 我怀疑你的问题是你的谓词格式。 %@ 需要一个 String 或一个 Swift 可以隐式转换为 String 的值,那么你会为 Int 使用什么占位符?

标签: core-data swiftui


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-05
      • 2023-04-04
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多