Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter object from Realm database in Swift

Tags:

swift

realm

I have realm array and I want to filter objects that contain id = 2 and user_id = 4. Please review my code below.

 for item in realm.objects(data.self).filter("id == 2 && user_id == 4") {
   print(item)
  }
like image 386
Inderpal Singh Avatar asked Oct 18 '25 13:10

Inderpal Singh


2 Answers

You are using the wrong operator in a realm, please check my answer below.

for item in realm.objects(data.self).filter("id == 2 AND user_id == 4") {
   print(item)
}
like image 194
iOS Avatar answered Oct 22 '25 06:10

iOS


Comparing the id with equality simultaneously with tow values seems to be not logical, id always has ONE value (2 OR 4) but not both, which means that your code should always return an empty array.

If you are aiming to filter the objects based on the value of id if its 2 or 4, you could do it like this:

for item in realm.objects(data.self).filter("id == 2 OR id == 4") {
   print(item)
}

Note that in the predicate you should type "AND" instead of "&&" and "OR" instead of "||". For more details, check: https://realm.io/docs/swift/latest/#filtering

which means that item would be any item that its id is 2 or 4.


Update:

Because of the change of the predicate from:

"id == 2 OR id == 4"

to

"id == 2 && user_id == 4"

What you should simply do -as I mentioned in the above note- is to change "&&" to "AND":

for item in realm.objects(data.self).filter("id == 2 AND user_id == 4") {
   print(item)
}
like image 23
Ahmad F Avatar answered Oct 22 '25 04:10

Ahmad F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!