Search code examples
iosrealm

Retrieving object properties with relation to their parent categories


I am new to realm and iOS development so I apologize in advance if something isn’t explained properly or is just incorrect.

I have 2 Realm Object classes:

class Category: Object {

@objc dynamic var name: String = ""
@objc dynamic var color: String = ""
let trackers = List<Tracker>()
}

and

class Tracker: Object {

@objc dynamic var timeSegment: Int = 0
var parentCategory = LinkingObjects(fromType: Category.self, property: 
"trackers")
}

I’m able to store new timeSegment properties consistently; however, the issue is that I cannot retrieve & display a collection of timeSegment values relating to their parentCategory. setting

var entries : Results<Tracker>?

produces all results for every category, which is the only result i'm able to pull so far after testing.

Any help is appreciated, and can follow up with any additional details. Thanks


Solution

  • You need to call objects on your Realm object with a filter for fetching only results that match a predicate. The realm object in this code is an instance of the Realm class.

    func getTrackersWithName(_ name: String) -> Results<Tracker> {
        return realm.objects(Tracker.self).filter("name = \"\(name)\"")
    }
    

    This tells Realm to fetch all objects that match the filter predicate. In this case, the filter predicate matches any object where the value of the "name" property matches the string that is passed into the method.