I'm trying to write my first Core Data driven document-oriented OSX application in Swift, as I want to get a bit more into Mac programming. The documents should be saved as XML files only, which I've managed to successfully configure.
The problem is that I want to pre-add some information to the document upon initializing without really "modifying" the document. The information is just required and should be in the document, but if the user creates and right away closes a document he should not be asked to save.
I've defined my Core Data data model and I've created NSManagedObject
subclasses from my model. In my document's init
method I'm doing this:
override init() {
super.init()
// Add your subclass-specific initialization here.
let newItem = NSEntityDescription.insertNewObjectForEntityForName("MyItem", inManagedObjectContext: self.managedObjectContext) as! MyItem;
newItem.descriptionText = "Item number 1";
newItem.itemNumber = 1;
}
This does add a new item to my document and when I save and re-load I can verify that the item is there. However, doing it this way, the document is marked "dirty" and upon closing it, the user is asked to save the changes.
How would I perform an initialization of my data model without actually marking the document as edited?
答案 0 :(得分:0)
对于那些感兴趣的人,我设法在我的案例中解决这个问题。首先,我将我的初始化代码移到了
convenience init?(type typeName: String, error outError: NSErrorPointer)
然后我暂时暂停撤消功能:
self.managedObjectContext.processPendingChanges();
self.undoManager.disableUndoRegistration();
在我进行更改后,我重新启用了撤消功能:
self.managedObjectContext.processPendingChanges();
self.undoManager.enableUndoRegistration();
到目前为止,这种方法运作良好。