ios - 如何在调用 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 ?
解决方案
没有内置的方法来验证谓词格式字符串是否是有效的谓词。对于格式字符串,您确实需要通过 (a) 在开发期间测试它们和 (b) 验证谓词中的替换值至少是正确的数据类型来验证谓词。
如果这是一个问题,您可能会发现以其他方式构建谓词比使用格式字符串更好。例如,使用NSComparisonPredicate
andNSCompoundPredicate
从NSExpression
. 代码会更加冗长,但通过在构造谓词时检查谓词的每个部分来确保谓词有效会更容易。
推荐阅读
- android - Firebase 数据库 android studio 在从服务器中提取数据时崩溃
- c# - 为什么 Stripe CLI HttpPost webhook 对 Asp.NET Core MVC 控制器的调用(事件)会在 System.Net.Security.dll 中出现“System.IO.IOException”错误?
- python - 烧瓶登录中基于角色的授权
- verilog - 如何在 Synopsys Verdi 中使用 Find Scope
- c++ - 在 C++ 中使用初始化列表填充多维结构数组的问题
- opengl - 在 OpenGL glTexImage2D() 中,如果“数据”指针为 NULL,最后两个枚举是否执行任何操作?
- pine-script - 结合STOCH RSI和Macd进行策略
- web-config - 最有效的 web.config 重定向
- javascript - 将函数参数传递给另一个函数
- mongodb - 为什么在聚合函数中使用 $project 时重命名 mongodb 中对象的子数组中的字段返回数组?