configurePersistentStoreCoordinator not called for saveAs NSPersistentDocument

后端 未结 4 1552
醉梦人生
醉梦人生 2021-01-21 11:18

I experience an odd behaviour regarding saving an NSPersistentDocument. I can create a new document which is autosaved without an issue. But when I save it write(to: ofTyp

4条回答
  •  情书的邮戳
    2021-01-21 11:46

    Could you try this nasty workaround?

    class CustomPersistentStoreCoordinator : NSPersistentStoreCoordinator {
    
      static var m1 : Method? = nil
      static var m2 : Method? = nil
    
      override func migratePersistentStore(_ store: NSPersistentStore, to URL: URL, options: [AnyHashable : Any]? = nil, withType storeType: String) throws -> NSPersistentStore {
        var opt: [AnyHashable : Any] = options ?? [:]
    
        if #available(OSX 10.13, *) {
          opt[NSBinaryStoreSecureDecodingClasses] = NSSet(array: [ NSColor.self ])
        }
    
        let m1 = CustomPersistentStoreCoordinator.m1!
        let m2 = CustomPersistentStoreCoordinator.m2!
        method_exchangeImplementations(m2, m1)
    
        let x = try self.migratePersistentStore(store, to: URL, options: opt, withType: storeType)
    
        method_exchangeImplementations(m1, m2)
        return x
      }
    }
    
    class Document: NSPersistentDocument {
    
      override init() {
        super.init()
    
        let s1 = #selector(NSPersistentStoreCoordinator.migratePersistentStore(_:to:options:withType:))
        let s2 = #selector(CustomPersistentStoreCoordinator.migratePersistentStore(_:to:options:withType:))
        let m1 = class_getInstanceMethod(NSPersistentStoreCoordinator.self, s1)!
        let m2 = class_getInstanceMethod(CustomPersistentStoreCoordinator.self, s2)!
        CustomPersistentStoreCoordinator.m1 = m1
        CustomPersistentStoreCoordinator.m2 = m2
        method_exchangeImplementations(m1, m2)
      }
    
      override func configurePersistentStoreCoordinator(for url: URL, ofType fileType: String, modelConfiguration configuration: String?, storeOptions: [String : Any]? = nil) throws {
        // keep yours
      }
    
    }
    

提交回复
热议问题