Oscar Apeland
Oscar Apeland

Reputation: 6662

Treat LinkingObjects as List

I have a model which references all object with a reference to itself. I thought I could use this property, LinkingObjects(fromType: Outfit.self, property: "clothes") as a List<Outfit> and just patch it right into my existing code.

Specifically I need to use the observe function of List. Is there any way to treat LinkingObjects equally as List?

Upvotes: 2

Views: 95

Answers (1)

Jay
Jay

Reputation: 35677

Let me give this a shot with an example - you may be approaching it backwards or I may not fully understand the question.

Suppose you have an Outfit class that has a List property of clothing objects

OutfitClass: Object {
   let clothingObjects = List<ClothingClass>
}

and then a class that holds each clothing type with a Link back to a particular OutfitClass. Now we have an inverse relationship.

ClothingClass: Object {
   @objc dynamic var description = ""
   let outfits = LinkingObjects(fromType: OutfitClass.self, property: "clothingObjects")
}

So each outfit has a list of clothes, jacket, button up shirt, tie etc and each of those items would know what outfit or outfits it belongs to.

That should satisfy the requirements where a model (the ClothingClass)

which references all objects (the OutfitClass) with reference to itself

I understand the objective is that you want to add an observer to all Outfit objects where a certain clothing item is referenced. So for example: the Red Tie Clothing Class object wants to observe all Outfits that reference that Red Tie.

So the approach is like this

First, we need to load in the Clothing Class object we are interested in

let redTieResults = realm.objects(ClothingClass.self).filter("descripton == 'Red Tie'")

no error checking here but let's assume that Red Tie is guaranteed to exist

let thisRedTie = redTieResults.first!

Now lets get the results, to which we can add an observer, for any Outfit class objects that have this specific Red Tie object in their List

let outfitResults = realm.objects(OutfitClass.self).filter("ANY clothingObjects == %@", thisRedTie)

then you add an observer to the outfitResults

Upvotes: 1

Related Questions