实例化NSManagedObject而不保存它 [英] Instantiate a NSManagedObject without saving it
本文介绍了实例化NSManagedObject而不保存它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个类:
@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中创建一个新用户:
I create a new User in a ViewController :
managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var aUser = User(id: "500T", context: managedObjectContext)
我有另一个班级Group,其中Group有很多用户。为了节省用户,我做了类似的事情。
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 ?
推荐答案
我找到了答案,并向用户init添加了一个needSave布尔值。也许这不是最好的答案,但是它有效。
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
}
}
这篇关于实例化NSManagedObject而不保存它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文