我的应用程序应该导入文本文件。使用NSOpenPanel,我可以选择文件,在关闭面板后,它应该逐个导入文件。这是通过向管理导入的观察者发送每个文件的通知self.nextFile()来完成的。
这是我的代码最坏的部分:
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
知道怎么同步吗?在闭包中@转义语句有帮助吗?
发布于 2022-11-25 10:39:54
我发现了根本原因:描述起来不太容易。
这是在我的代码中错误的位置初始化对象的副作用。
该应用程序是一个核心数据应用程序,当我打开多个文档时,我没有注意给每个文档自己的导入对象和NSManagedObjectContext。当涉及导入(next)文件的通知时,它会调用这两个文档。但是只有一个文件列表;第二个文件是空的。
经验教训:启动属于NSDocument文档而不是全局文档的对象(如附录委托或NSApp.)使用在苹果文档中描述的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
}
}
}https://stackoverflow.com/questions/74129287
复制相似问题