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

}
3
  • create one-to-many relationship as an option Commented Dec 6, 2014 at 7:33
  • @NeilGaliaskarov where do I create this relationship? possible in the interface builder? Commented Dec 6, 2014 at 7: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 Commented Feb 20, 2021 at 13:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.