Instantiate a NSManagedObject without saving it

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 ?

Answers


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

    }
}

Need Your Help

PHP (CakePHP) - Recognizing created form elements by JavaScript

javascript php html cakephp

I'm working on a CakePHP application. In my application, pages have a form tag with not elements inside. The form elements (inputs and etc) are created dynamically with JavaScript. So after some ce...

TFS Check In The request was aborted: The request was canceled

asp.net-mvc-4 tfs2012 rotativa

I'm trying to check in with my application but it is giving the following error: