Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm object predicate search is invalid

Tags:

swift

realm

Using Realm DB in a swift application. I'm trying to filter the results with a predicate as follows:

  class func fetchUsersFromDB(usersId: [String]) -> [User]{
        var users = [User]()
        let realm = Realm()
        let predicate = NSPredicate(format: "objectId IN %@", argumentArray: usersId)
        var allUsers = realm.objects(User).filter(predicate)
        users = Array(allUsers)
        return users
    }

But this won't compile. I get this error:

Terminating app due to uncaught exception 'Invalid value', reason: 'IN clause requires an array of items'

Any ideas what I'm doing wrong?

like image 344
denislexic Avatar asked Sep 14 '15 03:09

denislexic


2 Answers

Remove the argumentArray: label, as with it you're calling the wrong initializer for NSPredicate:

let predicate = NSPredicate(format: "objectId IN %@", usersId)

like image 57
Thomas Goyne Avatar answered Sep 19 '22 10:09

Thomas Goyne


As of Swift 3, just use Array(usersId) instead of usersId.

like image 45
IT Gypsy Avatar answered Sep 20 '22 10:09

IT Gypsy