首页 > 解决方案 > 如何在调用 fetch 之前验证 NSPredicate

问题描述

NSPredicate我使用自定义格式字符串创建搜索。有时这个字符串的语法是错误的,当我使用NSFetchRequest带有这个谓词的 a 执行 fetch 时,我得到 a NSInvalidArgumentException,例如当 key-path 不正确时。我宁愿验证这个谓词(YES如果格式正常,调用一些返回的方法),而不是抛出一个导致我的应用程序崩溃的异常。我能做些什么?

将调查改写为一个简单的问题:

我可以在不使应用程序崩溃的情况下验证谓词吗?

这是 Swift 中的示例代码:

let text = "price > 0.1" // ok, no syntax error
let text = "price > 'abc'" // error
let predicate = NSPredicate.init(format: text, argumentArray: [])
let request = NSFetchRequest<Fruit>.init(entityName: "Fruit")    
request.predicate = predicate
request.fetchLimit = 1
let fruit = try myContext.fetch(request) as [Fruit]  // exception thrown here that crashes app
// sometimes the exception can be caught with an obj-c try/catch
// sometimes it can't be caught, and causes program to terminate
// CAN WE HAVE A SOLUTION THAT NEVER CAUSES A CRASH ?

标签: ioscore-datanspredicatensfetchrequest

解决方案


没有内置的方法来验证谓词格式字符串是否是有效的谓词。对于格式字符串,您确实需要通过 (a) 在开发期间测试它们和 (b) 验证谓词中的替换值至少是正确的数据类型来验证谓词。

如果这是一个问题,您可能会发现以其他方式构建谓词比使用格式字符串更好。例如,使用NSComparisonPredicateandNSCompoundPredicateNSExpression. 代码会更加冗长,但通过在构造谓词时检查谓词的每个部分来确保谓词有效会更容易。


推荐阅读