为什么会出现 NSInvalidArgument 异常,原因:'Unable to parse the format string'

Why do I get an NSInvalidArgument Exception, reason: 'Unable to parse the format string'

虽然有很多关于这个主题的话题,但我一直没能找到我的问题的答案。当我在下面重构这个函数以将搜索参数传递给 NSPredicate 而不是对搜索值进行硬编码时,我现在得到错误:

*** 由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'Unable to parse the format string "formulaName == %0"'

func fetchFormula() {
    let fetchRequest = NSFetchRequest(entityName: "Formula")
    let calculation = calculator.selectedFormula
    let name = calculation.formulaName // name = Baechle
    let predicate = NSPredicate(format: "formulaName == %0", name)
    fetchRequest.predicate = predicate

    do {
      let results = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Formula]
      if (results != nil) {
        formula.text = results?[0].formulaName
      }
    } catch {
      fatalError("Error fetching data!")
    }
    return
  }

尽管我认为我的语法是正确的,但我已经尝试了我在 SO 和 Apple 文档中找到的几乎所有其他建议:

    let predicate = NSPredicate(format: "formulaName = 'Baechle'") // started with this and learned that this is a bad idea, but it worked
    let predicate = NSPredicate(format: "formulaName = %0", name) // only 1 '=' which results in the error I've described
    let predicate = NSPredicate(format: "formulaName == %0", name) // now 2 '==', but still doesn't work, produces "formulaName == %0"'and same error
    let predicate = NSPredicate(format: "formulaName == '%0'", name) // produces formulaName == "%0" resulting in no results

我没主意了。非常感谢任何帮助。

因为您一直在使用错误的格式说明符。它应该是 %@ 而不是 %0:

let predicate = NSPredicate(format: "formulaName == %@", name)

Predicate Format String Syntax