撤消故障:以编程方式初始化`NSPersistentDocument`,标题栏中没有“已编辑”标志

时间:2016-04-05 15:50:12

标签: swift cocoa core-data nsdocument

我有一个使用核心数据和NSPersistentDocument的小应用。对于新文档,我使用单个Settings元素初始化文档。我已经可以抑制初始化生成的撤销条目,但是......

奇怪的行为是这样的:文档以窗口标题中没有“已编辑”标志开头。只要我点击“编辑”菜单,就会出现“已编辑”标志,并且可能会突然发生撤消操作。

这是我的init()代码:

class Document: NSPersistentDocument {
    var settings: Settings! = nil
    override init() {
        super.init()
        do {
            let fetchSettings = NSFetchRequest(entityName: "Settings")
            let settingsList = try self.managedObjectContext!.executeFetchRequest(fetchSettings)
            precondition(settingsList.count < 2, "Too many settings object in the core data store.")
            if settingsList.count == 1 {
                settings = settingsList[0] as? Settings
                precondition(settings != nil)
            } else {
                managedObjectContext!.undoManager!.disableUndoRegistration()
                settings = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: self.managedObjectContext!) as? Settings
                precondition(settings != nil)
                // Here setup the "settings" object...
                settings.xxx = //...
                settings.yyy = //...
                managedObjectContext!.undoManager!.enableUndoRegistration()
            }
        } catch {
            preconditionFailure("Could not retrieve/create settings object because of an unknown core data error.")
        }
    }
    // ... more methods ...
}

问题是,一旦这个撤销条目出现,用户就可以撤消创建初始Settings对象,这会造成很多麻烦。

这是一个已知问题吗?如何防止这种情况发生?

这是一段演示效果的视频:https://youtu.be/O4lURxLAelE

1 个答案:

答案 0 :(得分:3)

呼叫

myModule.directive('timechart', function() {
    var linker = function(scope, element, attrs) {
        var xprop = scope.xprop;
        var yprop = scope.yprop;
        var title = scope.title
        var itemsToPlot = scope.itemsToPlot

        scope.$watch('itemsToPlot', function(newVal){
            itemsToPlot = newVal;
            // Just as a proof of concept:
            if( typeof itemsToPlot !== 'undefined' ) console.log(itemsToPlot);
        });
    };
    return {
        restrict: 'EA',
        scope: { 
            itemsToPlot: '=',
            title: '@',
            xprop: '@',
            yprop: '@'
        },
        link: linker
    };
});

[self.managedObjectContext processPendingChanges]; disableUndoRegistration之前。