实例化NSManagedObject而不保存它

时间:2015-07-11 15:24:19

标签: ios swift core-data ios8

我得到了一个类:

@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

    }
}

我在ViewController中创建了一个新用户:

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

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

我有另一个班级“Group”,其中Group有很多用户。为了节省用户,我做了类似

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

我不想保存所有用户。如何在不保存的情况下实例化用户?

2 个答案:

答案 0 :(得分:5)

我找到了答案,并向用户init添加了一个needSave布尔值。也许这不是最好的答案,但它正在发挥作用。

@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

    }
}

答案 1 :(得分:0)

@objc(User)
public class User: NSManagedObject {
    
    convenience init(id: String, context: NSManagedObjectContext?) {
        
        // Create the NSEntityDescription
        let entity = User.entity()
        self.init(entity: entity, insertInto: context)


        // Init class variables
        self.id = id
        
    }
}