SWIFT CoreData NSManagedObject

吃可爱长大的小学妹 提交于 2019-12-13 05:13:57

问题


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


回答1:


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.




回答2:


Hmmm. How about

var item = Item.insertItemWithTitle(title:"Item Title", context)
item.entityName()


来源:https://stackoverflow.com/questions/24792372/swift-coredata-nsmanagedobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!