Swift - iOS NSPredicate with optional NSDecimalNumber

1k views Asked by At

I'm trying to use the following NSPredicate with an NSDecimalNumber to check if a value is greater than 0.

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

"balance" is an Optional NSDecimalNumber attribute in a Core Data entity. 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. I suspect it is due to the "optional" nature of the attribute. Predicates comparing optional dates and NSNumber values are working with no problems.

Is there a different syntax I should be using to compare an Optional NSDecimalNumber?

2

There are 2 answers

0
N Gill On

Have just realised the issue was that I was attempting to use a transient attribute ("balance") in the fetch predicate. 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

            })!
1
Oleg Sherman On

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 i.e. 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.

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.