How to filter object from Realm database in Swift
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)
}
Filter in realm list swift
This was a very challenging query but I think I have a solution.
First however; Primitives in Realm Lists are not well supported and are not yet queryable. See here and this for more reading.
EDIT: Release 10.7 added support for filters/queries as well as aggregate functions on primitives so the below info is no longer completely valid. However, it's still something to be aware of.
So we will need to add another class to hold the string data
class StringClass: Object {
@objc dynamic var myString = ""
}
so the following class will be updated to match
class ParamsModel: BaseResponse {
var options = List<StringClass>()
}
Then to peform the query we need to leverage a Subquery due to the depth of the objects.
let predicate = NSPredicate(format: "SUBQUERY(customFields, $customField, ANY $customField.params.options.myString == 'custom').@count > 0")
let results = realm.objects(RetailerModel.self).filter(predicate)
This will return all Retailer Models whose CustomFieldsModel has a ParamsModel options List property StringClass myString property equal to 'custom'
Realm List Filter Swift
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
.
iOS Realm Filter objects in a list of a relationship
Realm doesn't have any sort of concept of a deep-filtered view, so you can't have a Results<Canteen>
which restricts the List
s contained in related objects to vegan meals.
There are several similar things which you can do. You could add inverse relationship properties, and then query Meal
objects instead:
class Canteen: Object {
dynamic var name: String?
let lines = List<Line>()
}
class Line: Object {
dynamic var name: String?
let meals = List<Meal>()
let canteens = LinkingObjects(fromType: Canteen.self, property: "lines")
}
class Meal: Object {
dynamic var name: String?
dynamic var vegan: Bool = false
let lines = LinkingObjects(fromType: Line.self, property: "meals")
}
let meals = realm.objects(Meal).filter("vegan = true AND ANY lines.canteens.name = %@", selectedCanteenType.rawValue)
(Or rather, you will be able to once Realm 0.102.1 is out; currently this crashes).
If you just need to iterate over the meals but need to do so from the Canteen down, you could do:
let canteens = realm.objects(Canteen).filter("name = %@ AND ANY lines.meals.vegan = true", selectedCanteenType.rawValue)
for canteen in canteens {
for line in canteen.lines.filter("ANY meals.vegan = true") {
for meal in line.meals.filter("vegan = true") {
// do something with your vegan meal
}
}
}
This unfortunately has some duplication due to needing to repeat the filter for each level of the references.
Realm Swift Filter Query Based On List Property
Let me restate the question;
You want an artist to be able to query for all new shows in cities
they are interested in where they have not yet responded.
If that's the question, let me start with some simple sample data
Two artists that have each have two cities if interest
let a0 = Artist()
a0.name = "Jim"
a0.citiesOfInterest.append(objectsIn: ["Austin", "Memphis"])
let a1 = Artist()
a1.name = "Henry"
a1.citiesOfInterest.append(objectsIn: ["Austin", "Memphis"])
and then two shows, one in each city
let s0 = Show()
s0.name = "Austin Show"
s0.city = "Austin"
let s1 = Show()
s1.name = "Memphis Show"
s1.city = "Memphis"
but artist a0 (Jim) has responded to the s0 (Austin) show
let r0 = ArtistResponse()
r0.show = s0
r0.artist = a0
r0.available = true
s0.artistResponses.append(r0) //jim responded to the Austin show
The result we want is that when Jim the artist logs on, he will see the Memphis show because he already responded to the Austin show.
let realm = try! Realm()
if let jim = realm.objects(Artist.self).filter("name == 'Jim'").first {
let myCities = jim.citiesOfInterest
let showResults = realm.objects(Show.self)
.filter("city IN %@ AND !(ANY artistResponses.artist.name == 'Jim')", myCities)
for show in showResults {
print(show.name)
}
}
And the output is
Memphis Show
We first get the Jim's cities of interest as an array, then we filter the shows that match those cities of interest but where there are no artist responses associated with Jim. This filter was based on the name but you could use the Artist id or even the Artist object itself as the comparator.
How to filter Realm objects by list
try this solution
If you use a to-many relationship, You use an ANY
operator
Please read this well so you understand what to use because there is another operator ex ALL,ANY,NONE
Predicate Programming Guide
private func getDeviceContacts(_ phoneNumbers: [Int64]) -> [DeviceContactModel] {
do {
let realm = try Realm()
let deviceContacts = Array(realm.objects(DeviceContactModel.self).filter("ANY phones.fullNumber IN %@", phoneNumbers))
return deviceContacts
} catch {
debugPrint(error.localizedDescription)
return []
}
}
How to filter a realm subclass swift
There are actually multiple questions here. First we need to change the use of of the word subclass
to instance
. There are no subclasses in the question.
Note that Realm is conceptually an `Object' database so we're going to use the word 'object' to refer the objects stored in Realm (the 'instances' when they've been loaded in to memory)
I will rephrase each for clarity:
- How do I return all
SubscriptionClass
objects?
let results = realm.objects(SubscriptionClass.self)
- How do I return one specific
SubscriptionClass
object if I know the
primary key?
let oneObject = realm.object(ofType: SubscriptionClass.self, forPrimaryKey: theObjectsPrimaryKey)
- How do I return all of the
SubscriptionClass
objects that match a
specific criteria; where the question property equalsWhat is 5*5
let results = realm.objects(SubscriptionClass.self).filter("question == 'What is 5*5'")
and I will slide in #4: this queries for all questions as in #3 but only returns the very first one it finds. This can be dangerous because Realm objects are unordered so if there are ever more than one object, it could return a different first object each time it's used
if let oneObject = realm.objects(SubscriptionClass.self).filter("question == 'What is 5*5'").first {
//do something with the object
}
Subclass:
A subclass inherits the superclass's functionality and extends it to provide additional functionality. Here's a subclass that adds a difficulty property to a subclass of SubscriptionClass (the 'super class')
class SubscriptionWithDifficultySubClass: SubscriptionClass {
var difficulty = "" //Easy, Medium, Hard etc
}
and then a different subclass that provides a subject property:
class SubscriptionWithSubjectSubClass: SubcriptionClass {
var subject = "" //Math, Grammar, Science etc
}
Swift Realm filter List property using an Array
You can't achieve your goals using predicate with Realm because Realm have a lot of limitations using Predicates
and the missing ability to handle computed properties but you can use this way as a workarround
let filterList = ["A","B"]
let realmList = realmInstance?.objects(MyDTO.self)
let filteredArray = Array(realmList!).filter({Array($0.tags).map({$0.tagName}).sorted().joined().contains(filterList.sorted().joined())})
here Array($0.tags).map({$0.tagName}).sorted().joined()
we get the tags array and convert it with map to an array of Strings then we sort that array of Strings (this will ensure that only matters the TAGS in the array not the order) and after that we convert that sorted array in a String by example your array of tags.tagName is ["B","A","C"] and after this you will get "ABC" as STRING
after that we check if that STRING contains your filterList.sorted().joined() the same procedure that was explained before
so if your filterList have ["B","C","A"] you will get "ABC"
and the we check if "ABC" contains "ABC" if so then is included in final result
Realm filter results based on values in child object list
Here's one possible solution - add a reverse refererence to the restaurant for each meal object
class Restaurant: Object {
@objc dynamic var name: String? = nil
let meals = List<Meal>()
}
class Meal: Object {
@objc dynamic var mealName: String? = nil
let tag = RealmOptional<Int>()
@objc dynamic var restaurant: Restaurant? //Add this
}
then query the meals for that restaurant with the tags you want.
let results = realm.objects(Meal.self).filter("restaurant.name == %@ AND tag IN %@", "Foo", [1,2])
LinkingObjects could also be leveraged but it depends on what kind of queries will be needed and what the relationships are between Restaurants and Meals - I am assuming 1-Many in this case.
if you want ALL restaurants, then LinkingObjects is the way to go.
Edit:
Thought of another solution. This will work without adding a reference or an inverse relationship and will return an array of restaurants that have meals with the selected tags.
let selectedTags = [1,2]
let results = realm.objects(Restaurant.self).filter( {
for meal in $0.meals {
if let thisTag = meal.tag.value { //optional so safely unwrap it
if selectedTags.contains(thisTag) {
return true //the tag for this meal was in the list, return true
}
} else {
return false //tag was nil so return false
}
}
return false
})
Related Topics
Codable: Does Not Conform to Protocol 'Decodable'
Issues Scaling Sprite Width to Screen Width
Url(String:) Cannot Call Value of Non-Function Type 'string'
How to Add a Menu to The Application in The Dock
Errors When Update Code to Avoid Deprecation Warnings Withunsafemutablebytes in Swift 5
Enum Initialized with a Non-Existent Rawvalue Does Not Fail and Return Nil
How to Solve This Error: Thread 1: Exc_Resource Resource_Type_Memory (Limit=650 Mb, Unused=0X0)
Weak Reference to Closure in Swift
Xcode 7 Cast from Xcuielement to Unrelated Type 'string' Always Fails While Fetching JSON
Swift - Measurement Convert(To:) Miles to Feet Gives Wrong Result
Reading from Txt File in Swift 3
Convenience Failable Initializers Assign Self
Event Scrolling (Scrollviewdidscroll) Never Called - Swift 3
Getting Common Data from Two Different Types of Array
Swift 4 Date Picker Wrong Value Using Minuteinterval
How to Invoke Method with Cvalistpointer Parameters in Swift