barnabus
barnabus

Reputation: 882

Filtering on RealmOptional removes values of nil, while CoreData predicate does not

I've ported code from CoreData to Realm and everything is working great aside from 1 final issue.

Filtering when using a RealmOptional is removing all objects that have a value equal to nil.

For instance, .filter("price <= 10.0") is removing from the results set, all objects whose price is nil. This behaviour did not happen in CoreData when using NSFetchedResultsController and NSPredicates, so I'm wondering if this is expected behaviour for Realm?

The Object is as follow a RealmOptional<Double> in the example below:

class Product : Object, Mapper
{
    var price = RealmOptional<Double>() {
        // Using ObjectMapper library to map JSON to Realm hence willSet
        willSet {
            self.price = newValue
        }
    }
}

I would expect results to return all Products that have price < 10.0 including those with nil values.

Is this expected behaviour or simply a bug?

Upvotes: 0

Views: 2038

Answers (1)

marius
marius

Reputation: 7806

That objects with null values are not included if you filter by a numeric comparison operator is the expected behavior. You can add OR price = nil if you'd like to include the objects where the price is nil. Like the following:

let free_or_cheap_products = realm.objects(Product)
    .filter("product <= 10 || product = nil")

Upvotes: 3

Related Questions