简体   繁体   English

Swift-具有可选NSDecimalNumber的iOS NSPredicate

[英]Swift - iOS NSPredicate with optional NSDecimalNumber

I'm trying to use the following NSPredicate with an NSDecimalNumber to check if a value is greater than 0. 我正在尝试将以下NSPredicateNSDecimalNumber一起使用,以检查值是否大于0。

let addPredicate:NSPredicate = NSPredicate(format:"balance > 0", argumentArray: [])

"balance" is an Optional NSDecimalNumber attribute in a Core Data entity. “余额”是核心数据实体中的一个可选NSDecimalNumber属性。 The result is coming up empty (no errors), even when I try balance < 0, or balance == 0. I can confirm that there are no null balance records. 结果是空的(没有错误),即使我尝试将余额<0或余额== 0也可以。我可以确认没有空余额记录。 I suspect it is due to the "optional" nature of the attribute. 我怀疑这是由于属性的“可选”性质。 Predicates comparing optional dates and NSNumber values are working with no problems. 比较可选日期和NSNumber值的谓词没有任何问题。

Is there a different syntax I should be using to compare an Optional NSDecimalNumber ? 我应该使用不同的语法来比较Optional NSDecimalNumber吗?

The fact that it is optional should not make a difference. 它是可选的这一事实不应有任何区别。 There is a different syntax you can use but yours should work too. 您可以使用其他语法,但也可以使用。 You can try the object syntax: 您可以尝试使用对象语法:

NSPredicate(format:"balance > %@", argumentArray: [NSDecimalNumber.zero])

But it does exactly the same as your predicate and should return the same result. 但是它的作用与您的谓词完全相同,并且应返回相同的结果。

If you tried all the options ie grater than 0 and lower than zero and equal to zero (the equal to zero should also return entities with nil balance!), then the most simple explanation that there are no objects at all. 如果您尝试了所有选项,例如,大于0且小于零且等于零(等于零也应返回平衡为零的实体!),那么最简单的解释就是根本没有对象。

I don't think that the predicate is the problem, I would suggest you to check if there is some problem creating/saving new entities or maybe they are deleted ... 我认为谓词不是问题,我建议您检查创建/保存新实体时是否存在问题,或者将其删除...

Hope it helps. 希望能帮助到你。

Have just realised the issue was that I was attempting to use a transient attribute ("balance") in the fetch predicate. 刚刚意识到问题是我试图在提取谓词中使用瞬态属性(“ balance”)。 So instead I have used a filter on the fetched results and this gives the correct output. 因此,相反,我对获取的结果使用了过滤器,从而给出了正确的输出。

filteredItems = (fetchedResultsController.fetchedObjects?.filter { item in
            let searchResult:Bool = (item.balance!.compare(NSDecimalNumber.zero) == .orderedDescending)

            return searchResult

            })!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM