Pradeep Bishnoi
Pradeep Bishnoi

Reputation: 1873

Realm List Filter Swift

var numbersDetail = List is type of ContactDetail()
let predicate = NSPredicate(format: ContactDetail.NUMBER + " = %@", formattedNumber!)
let realmContactDetail = numbersDetail.filter(predicate).first

Fetching ERROR :

throw RLMException("This method may only be called on RLMArray instances retrieved from an RLMRealm");

Upvotes: 3

Views: 3690

Answers (1)

TiM
TiM

Reputation: 16021

This error occurs if you try and perform a query on a Realm Swift List object (Which are actually Objective-C RLMArray objects under the hood) before its parent object has been added to a Realm.

class Person: Object {
  dynamic var name = ""
  dynamic var picture: NSData? = nil // optionals supported
  let dogs = List<Dog>()
}

let dog = Dog()
dog.name = "Rex"

let person = Person()
person.dogs.append(dog)

let rex = person.dogs.filter("name == 'Rex'") // QUERY WILL TRIGGER EXCEPTION AT THIS POINT

let realm = try! Realm()
try! realm.write {
    realm.add(person)
}

let rex = person.dogs.filter("name == 'Rex'") // Query will now work as expected

In a nutshell, you need to make sure that numbersDetail belongs to a Realm before you perform that query. You can easily test this by checking numbersDetail.realm != nil.

Upvotes: 1

Related Questions