Reputation: 73
I have a Custom NSManagedObject (in Swift) and looks like this
import UIKit
import CoreData
@objc(Item)
class Item: NSManagedObject {
@NSManaged var title:String
func entityName() -> String{
println("Entity Name")
let item = "Item"
return item
}
func insertItemWithTitle (title: String? , managedObjectContext:NSManagedObjectContext) -> Item{
println(title)
let item = NSEntityDescription.insertNewObjectForEntityForName(entityName(), inManagedObjectContext: managedObjectContext) as Item
if title {
item.title = title!
}
return item
}
}
What is The proper way to Initialize something like this and use it
Upvotes: 0
Views: 516
Reputation: 2327
Instantiation (e.g. init
) is taken care of by Core Data, so a class factory method is recommended for what you want to do. For example:
@objc(Item)
class Item: NSManagedObject {
@NSManaged var title:String
class func entityName() -> String {
return "Item"
}
class func insertItemWithTitle(title: String, managedObjectContext:NSManagedObjectContext) -> Item {
let item = NSEntityDescription.insertNewObjectForEntityForName(Item.entityName(), inManagedObjectContext: managedObjectContext) as! Item
item.title = title
return item
}
}
You might also make parameter title
NOT optional since the managed attribute title
is required. Or, you can make title
optional, but make sure your model is updated to reflect this change.
Upvotes: 1
Reputation: 80265
Hmmm. How about
var item = Item.insertItemWithTitle(title:"Item Title", context)
item.entityName()
Upvotes: 0