I got data loading working (-ish?) in my NSDocument-based app. But soon after
the window opens, the “Edited” status appears. Here’s the method:
> override func read(from data: Data, ofType typeName: String) throws {
> guard UTTypeConformsTo(typeName as CFString,
> Names.internationalEmailMessageUTI as CFString) else {
> throw CocoaError(.fileReadUnknown)
> }
>
> // Parse the incoming data.
> let operationalMessage = InternetMessageReadingOperation(data: data)
> operationalMessage.start()
> assert(operationalMessage.isFinished)
> guard !operationalMessage.isCancelled else { throw
> CocoaError(.userCancelled) }
>
> // Create a document message object from the operation message object.
> var backgroundMessage: RawMessage!
> var backgroundError: Error?
> let backgroundContext = self.container.newBackgroundContext()
> backgroundContext.performAndWait {
> backgroundMessage = RawMessage(context: backgroundContext)
> // ...
>
> do {
> try backgroundContext.save()
> } catch {
> backgroundError = error
> }
> }
> guard backgroundError == nil else { throw backgroundError! }
>
> // Replace the current message with a copy of the new one.
> let mainContext = self.container.viewContext
> mainContext.performAndWait {
> self.undoManager?.disableUndoRegistration()
> defer { self.undoManager?.enableUndoRegistration() }
>
> let oldMessage = self.message
> self.message = mainContext.object(with:
> backgroundMessage.objectID) as! RawMessage
> mainContext.delete(oldMessage!)
> try! mainContext.save() // Can't really recover; the new message
> is already in.
> }
> }
The Document guide mentioned something about disabling undo during data load.
Am I doing it right here? I’ve heard that “read(from: ofType:)” may be called
during other times besides initial file load, so I want to get the swap-out
functionality correct. Here’s a relevant part of “init()”:
> // Finish preparing the main context and seed the root message object.
> let mainContext = self.container.viewContext
> mainContext.performAndWait {
> self.message = RawMessage(context: mainContext)
> do {
> try mainContext.save()
> } catch let saveError {
> self.initError = saveError
> }
> }
> mainContext.automaticallyMergesChangesFromParent = true
> mainContext.undoManager = self.undoManager
Is “automaticallyMergesChangesFromParent” messing me up? Or is there some
change-count reset function I should always call at the end?
—
Daryle Walker
Mac, Internet, and Video Game Junkie
darylew AT mac DOT com
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]