簡體   English   中英

NSOpenPanel 有時不返回 NSOpenPanel.urls

[英]NSOpenPanel sometimes does not return NSOpenPanel.urls

我的應用程序應該導入文本文件。 使用NSOpenPanel我可以 select 個文件,關閉面板后,它應該一個接一個地導入文件。 這是通過將每個文件的通知self.nextFile()發送給管理導入的觀察者來完成的。

這是我的代碼 nippest:


    func selectFiles() {
        fileIndex = 0
        fileList  = [URL]()
        
        recordsImported = 0
        numberOfLines = 0
        let openPanel = NSOpenPanel()
        openPanel.allowsMultipleSelection = true
        openPanel.canChooseDirectories = false
        openPanel.canCreateDirectories = false
        openPanel.canChooseFiles = true
        //openPanel.allowedFileTypes = ["csv"]  // deprecated !
        openPanel.delegate = self
        openPanel.accessoryView = loadAccessoryVC!.view as NSView
        openPanel.beginSheetModal(for:(NSApplication.shared.mainWindow)!) { (response) in
            if response == .OK {
                self.fileList = openPanel.urls
                self.nextFile(notification: Notification(name:Notification.Name("next file")))
            }
            
            openPanel.close()
        }

大多數時候它工作正常,但有時openPanel.urls是空的——尤其是當我的列表超過 20 個文件時。 調用 self.nextFile()之前,打開的面板似乎尚未完成。

  • Xcode 版本:14.01
  • 部署目標:MAC OS 10.15

知道如何同步嗎? 閉包中的@escaping 語句有幫助嗎?

我找到了根本原因:它不是很容易描述。
這是在我的代碼中錯誤的位置初始化對象的副作用。
該應用程序是一個 Core Data 應用程序,當我打開多個文檔時,我沒有注意給每個文檔單獨導入 object 和 NSManagedObjectContext。 當涉及導入(下一個)文件的通知時,它要求兩個文件。 但是只有一個有文件列表; 第二個是空的

經驗教訓:在 NSDocument 中啟動屬於文檔的對象,而不是全局對象(如在 Appdelegate 或 NSApp 中)。使用 Apple 文檔中描述的 make WindowController。 :

override func makeWindowControllers() {
    // Returns the Storyboard that contains your Document window.
    let storyboard = NSStoryboard(name: "Main", bundle: nil)
    if let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as? NSWindowController {
        addWindowController(windowController)
        

        if let contentVC = windowController.contentViewController as? MyViewManager {
            // NSPersistentdocument creates the managedObjectComtext itself:
            contentVC.representedObject = self.managedObjectContext
            contentViewController = contentVC                
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM