首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSOpenPanel有时不返回NSOpenPanel.urls

NSOpenPanel有时不返回NSOpenPanel.urls
EN

Stack Overflow用户
提问于 2022-10-19 17:05:47
回答 1查看 20关注 0票数 0

我的应用程序应该导入文本文件。使用NSOpenPanel,我可以选择文件,在关闭面板后,它应该逐个导入文件。这是通过向管理导入的观察者发送每个文件的通知self.nextFile()来完成的。

这是我的代码最坏的部分:

代码语言:javascript
复制
    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()之前,打开的面板看起来还没有完成。

14.01

  • deployment目标:MacOS10.15

知道怎么同步吗?在闭包中@转义语句有帮助吗?

EN

回答 1

Stack Overflow用户

发布于 2022-11-25 10:39:54

我发现了根本原因:描述起来不太容易。

这是在我的代码中错误的位置初始化对象的副作用。

该应用程序是一个核心数据应用程序,当我打开多个文档时,我没有注意给每个文档自己的导入对象和NSManagedObjectContext。当涉及导入(next)文件的通知时,它会调用这两个文档。但是只有一个文件列表;第二个文件是空的。

经验教训:启动属于NSDocument文档而不是全局文档的对象(如附录委托或NSApp.)使用在苹果文档中描述的make WindowController。:

代码语言:javascript
复制
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                
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74129287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档