Instantiate a NSManagedObject without saving it

穿精又带淫゛_ 提交于 2019-12-06 08:51:37

问题


I got a class like :

@objc(User)
class User: NSManagedObject {

    @NSManaged var id: String

    //MARK: - Initialize
    convenience init(id: String,  context: NSManagedObjectContext?) {

        // Create the NSEntityDescription
        let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: context!)


        // Super init the top init
        self.init(entity: entity!, insertIntoManagedObjectContext: context)


        // Init class variables
        self.id = id

    }
}

I create a new User in a ViewController :

managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

var aUser = User(id: "500T", context: managedObjectContext)

I have another class "Group" where Group have many Users. To save user I do something like

aGroup!.users = NSSet(array: users!)
!managedObjectContext.save

I don't want to save all users. How can I instantiate a user without saving it ?


回答1:


I found my answer and add a needSave boolean to the user init. Maybe it's not the best answer but it's working.

@objc(User)
class User: NSManagedObject {

    @NSManaged var id: String

    //MARK: - Initialize
    convenience init(id: String, needSave: Bool,  context: NSManagedObjectContext?) {

        // Create the NSEntityDescription
        let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: context!)


        if(!needSave) {
            self.init(entity: entity!, insertIntoManagedObjectContext: nil)
        } else {
            self.init(entity: entity!, insertIntoManagedObjectContext: context)
        }

        // Init class variables
        self.id = id

    }
}


来源:https://stackoverflow.com/questions/31358692/instantiate-a-nsmanagedobject-without-saving-it

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