yerpy
yerpy

Reputation: 1446

Save object in Core Data

Let's say i have class which looks like this :

class A { 
   var property1:Int
   var property2:String

   init(property1: Int, property2: String) {
      self.property1 = property1
      self.property2 = property2   
   }
}

(...)

let a = A(property1: 10, property2: "Smth")

Is it the way to save that object in CoreData ? Do i have to create via NSManageObject Subclass new class with this name and then do everything from the beginning ? Or there is a way to convert class to match it without changes ? Btw. via this generator in the latest update is a bug which says that those class is ambiguous :o

Thanks in advance!!

Upvotes: 0

Views: 2317

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70976

You do need to have an NSManagedObject or a subclass, but you can't have two classes with the same name. With Core Data you normally define an entity type in the Core Data model editor, and then create a subclass to match that entity (Xcode usually creates the subclass automatically these days).

It's very unusual to have a second non-managed class that mirrors the Core Data object. You can use an NSManagedObject subclass on its own. You can still have property1 and property2, but your initializer will have to change. For managed objects you must have a managed objet context at initialization, which generally means including one as an argument to the initializer.

You might find it worthwhile to take a look at Apple's Core Data Programming Guide.

Upvotes: 1

Related Questions