The Nomad The Nomad - 1 year ago 163
Swift Question

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


Core Data
, I want to store an array of custom
objects in my custom
class in the database.

variable is a
. I want to be able to store
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

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 Source

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 = as? Game

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download