Traversing 'LinkingObjects' to retrieve "parent" category object


#1

To help with my question, refer to the model below.

class Category: Object {
@objc dynamic var parentName: String = “”
let subCategories = List()
}

class SubCategory: Object {
@objc dynamic var subCategoryName: String = “”
let parent = LinkingObjects(fromType: Category.self, property: “subCategories”)
}

My question is, when I create a Subcategory object, is there a way I can access the parent object by traversing the LinkingObjects property so I can assign the parent category to parentCategorySelected property as seen in the picture? For example, I am creating a CRUD app that allows a user to select either a parent category or a subcategory of the parent and I want to to be able to filter down on these tasks either by parent category as a whole and individual categories. Any suggestions?


#2

Assuming Swift 4, that code pretty much works for what you are asking with a slight mod… if I am understanding the question. The question mentions a ‘parentCategorySelected’ but that property isn’t shown in code. However, it may not be needed since the child SubCategory knows who it’s parent Category is.

I modified the Category’s SubCategory’s List property with a < SubCategory >:

class Category: Object {
    @objc dynamic var parentName: String = ""
    let subCategories = List<SubCategory>()
}

class SubCategory: Object {
    @objc dynamic var subCategoryName: String = ""
    let parent = LinkingObjects(fromType: Category.self, property: "subCategories")
}

Then create the objects like this

let c = Category()
c.parentName = "cat 0"
        
let sc = SubCategory()
sc.subCategoryName = "subcat 0"
        
c.subCategories.append(sc)

and write them to Realm

do {
      let realm = try Realm()
      try! realm.write {
         realm.add(c)
      }     
    } catch let error as NSError {
       print(error.localizedDescription)
    }
}

I can then transverse the SubCategory LinkingProperties back to the parent object like this

let realm = try! Realm()
let results = realm.objects(SubCategory.self)
let sc = results.first
print(sc) //prints the subcategory
        
let p = sc?.parent.first
print(p) //prints the subcategory's parent

Let me know if I am too far off and will edit accordingly.


#3

Thank you so much Jay. That’s exactly what I was looking for. :grinning: