The Nomad The Nomad - 4 months ago 40
Swift Question

Swift: how to store array of custom objects in Core Data?

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

}

Answer

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.

Comments