2

Using Swift and Core Data, I want to store an array of custom Game objects in my custom User class in the database.

The GameOwned variable is a Transformable. I want to be able to store [Game] inside the database.

How can I go about achieving this? Is there anything special I need to do in order to be able to read it once I pull it from the database other than casting it to [Game]?

User Class

class User: NSManagedObject {

    @NSManaged var gameOwned: AnyObject
}

Game Class

class Game: NSManagedObject {

    @NSManaged var coverPhoto: String
    @NSManaged var genre: String
    @NSManaged var id: String
    @NSManaged var isActive: NSNumber
    @NSManaged var isOwned: NSNumber
    @NSManaged var name: String
    @NSManaged var platform: String

}
The Nomad
  • 7,155
  • 14
  • 65
  • 100
  • create one-to-many relationship as an option – Neil Galiaskarov Dec 06 '14 at 07:33
  • @NeilGaliaskarov where do I create this relationship? possible in the interface builder? – The Nomad Dec 06 '14 at 07:37
  • @TheNomad Can you please post step by step solution about how you achieved this one. As at my end, I have "Album" and "AlbumImages" two entities. I want to access an array of album images using album entity. Can you please let me know the steps and the things I need to add to the class files – Mitesh Dobareeya Feb 20 '21 at 13:38

1 Answers1

3

Your Game is already a Core Data object. You need to set a relationship between User and Game. It should be to-many, and you could call it games.

Relationships are very basic Core Data concepts. You do this in the Core Data model editor in Xcode. Please read up on this first in the Core Data Programming Guide.

Once you have this setup, you can access the related items very simply.

var aGame = user.games.anyObject as? Game

The above is optional because there might be no games, etc.

Mundi
  • 79,884
  • 17
  • 117
  • 140