如何在调用fetch之前验证NSPredicate [英] How to validate NSPredicate before calling fetch

查看:88
本文介绍了如何在调用fetch之前验证NSPredicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用自定义格式字符串创建搜索 NSPredicate 。有时,此字符串的语法是错误的,当我使用带有该谓词的 NSFetchRequest 执行提取时,会得到 NSInvalidArgumentException ,例如,当密钥路径不正确时。我宁愿宁愿验证此谓词(调用某种方法,如果格式可以,则返回 YES ),而不是抛出使我的应用程序崩溃的异常。我该怎么办?

I create a search NSPredicate using a custom format string. Sometimes the syntax of this string is wrong and when I execute a fetch using a NSFetchRequest with this predicate I get a NSInvalidArgumentException, for example when the key-path is incorrect. I would much rather prefer to validate this predicate (call some method that returns YES if format is ok), than have an exception thrown that crashes my app. What can I do?

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

To rephrase the inquiry into a simple question:

我可以不使用以下内容来验证谓词吗?

Can I validate the predicate without potentially crashing the app?

以下是Swift中的示例代码:

Here is example code in 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)验证谓词中的替换值至少是正确的数据类型。

There's no built-in way to validate that a predicate format string is a valid predicate. With format strings, you really need to validate the predicates by (a) testing them during development and (b) verifying that substitution values in predicates are at least the right data type.

如果这是一个问题,您可能会发现以其他方式而不是使用格式字符串来构建谓词会更好。例如,使用 NSComparisonPredicate NSCompoundPredicate NSExpression 。该代码将更加冗长,但是在构造它时,通过检查谓词的每个部分,可以更轻松地确保谓词有效。

If that's a problem, you might find it better to build your predicates in other ways, instead of with format strings. For example, use NSComparisonPredicate and NSCompoundPredicate to build the predicates from instances of NSExpression. The code will be much more verbose, but it will be easier to ensure that your predicate is valid by checking each part of it as you construct it.

这篇关于如何在调用fetch之前验证NSPredicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆