【问题标题】:Building an NSCompoundPredicate from array values in Swift在 Swift 中从数组值构建 NSCompoundPredicate
【发布时间】:2014-07-26 18:00:13
【问题描述】:

列表项

所以我试图在 Swift 中设置一个具有多个条件的请求。 SQL 相当于:

select BOARDID
 from BOARD
 where BOARDID not like "someBoard"
 and BOARDID not like "anotherBoard"
 ..

我有一个字符串数组,我正在尝试遍历每个字符串以创建一个 subPredicate,将其添加到一个 CompoundPredicate,然后使用该 CompoundPredicate 创建一个获取请求:

let openBoards = ["someBoard", "anotherBoard", "etc"],
    request = NSFetchRequest(entityName: "Board")

var openBoardsSubPredicates: Array = [],
    error: NSError? = nil

for board in openBoards {
    var subPredicate = NSPredicate(format: "boardID not like '\(board)'")
    openBoardsSubPredicates += subPredicate
}

request.predicate = NSCompoundPredicate.andPredicateWithSubpredicates(openBoardsSubPredicates)

但是,它在 var subPredicate 行失败..

谢谢!

【问题讨论】:

  • “失败”是什么意思?更加详细一些。是编译器错误吗?它在运行时崩溃吗?它报告了什么错误?
  • 我收到以下两个错误:1.引发了未捕获的异常,2.无法解析格式字符串“boardID not like 'someBoard'”

标签: core-data swift nspredicate nscompoundpredicate


【解决方案1】:

错误告诉您问题所在。您提供的格式不是有效格式。具体来说,没有“不喜欢”的比较。你必须在外面做“不”:

NSPredicate(format: "not (boardID like %@)", board)

正如下面提到的@MartinR,您可以让 NSPredicate 自动转义特殊字符,这样它们就不会通过插入变量而不是使用字符串插值来干扰谓词。

【讨论】:

  • 谢谢!我认为格式字符串与 sqlite 语法相关:(
  • 更好:NSPredicate(format: "not (boardID like %@)", board)。否则,如果“board”包含像单引号这样的特殊字符,它会崩溃。永远不要混合字符串格式(或者在这种情况下,字符串插值)和谓词格式。
  • @Pirijan,你可以在Apple's Documentation获得更多关于NSPredicate格式的信息
  • @drewag:次要的挑剔:NSPredicate(format: ...) 不会“自动转义特殊字符”。谓词是一种树状结构(使用 NSPredicate 的各种子类,如 NSComparisonPredicate、NSCompoundPredicate...),而不是字符串。 NSPredicate(format: ...) 是一种从格式字符串和参数创建谓词的便捷方法。如果格式字符串包含键或值,则必须正确转义。如果键和值作为参数提供,则无需转义它们。
  • @MartinR,我不确定你在说什么。根据文档“argList:要替换为 predicateFormat 的参数。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多