gpt4 book ai didi

Swift - 使用 performSelectorOnMainThread

转载 作者:搜寻专家 更新时间:2023-11-01 07:23:51 25 4
gpt4 key购买 nike

我正在尝试将 – performSelectorOnMainThread:withObject:waitUntilDone: 用于我在 Swift 中开发的 Cocoa 应用程序。我需要应用程序等到工作完成。无论如何,我有以下代码行。

func recoverData(path:String) -> Void {
let sheetRect:NSRect = NSMakeRect(0,0,400,114)
let progSheet:NSWindow = NSWindow.init(contentRect:sheetRect, styleMask:NSTitledWindowMask,backing:NSBackingStoreType.Buffered,`defer`:true)
let contentView:NSView = NSView.init(frame:sheetRect)
let progInd:NSProgressIndicator = NSProgressIndicator.init(frame:NSMakeRect(190,74,20,20))
progInd.style = NSProgressIndicatorStyle.SpinningStyle
let msgLabel:NSTextField = NSTextField.init(frame:NSMakeRect(20,20,240,46))
msgLabel.stringValue = "Copying selected file..."
msgLabel.bezeled = false
msgLabel.drawsBackground = false
msgLabel.editable = false
msgLabel.selectable = false
contentView.addSubview(msgLabel)
contentView.addSubview(progInd)
progSheet.contentView = contentView

self.window.beginSheet(progSheet) {(NSModalResponse returnCode) -> Void in
progSheet.makeKeyAndOrderFront(self)
progInd.startAnimation(self)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority,0)) {

//////////////////////////////////////////////////////////////////////////////////////////////////
self.performSelectorOnMainThread(Selector(self.readData(path)),withObject:path,waitUntilDone:true)
//////////////////////////////////////////////////////////////////////////////////////////////////

}

dispatch_async(dispatch_get_main_queue()) {
progInd.indeterminate = true
self.window.endSheet(progSheet)
progSheet.orderOut(self)
}
}
}

func readData(path:String) -> Void {
print("Hello!?")
}

我不确定如何将 path 传递给 readData。 Xcode 要求我将参数设置为 nil 或 nothing 以外的值。在 Objective-C 中,它将是

[self performSelectorOnMainThread:@selector(readData:) withObject:path waitUntilDone:YES];

无论如何,应用程序永远不会到达 readData。我做错了什么?

感谢您的帮助。

最佳答案

为什么不

self.window.beginSheet(progSheet) {(returnCode) -> Void in
dispatch_async(dispatch_get_main_queue()) {
progInd.startAnimation(self)
self.readData(path)
progInd.indeterminate = true
}
}

在某些时候,您必须调用 self.window.endSheet(progSheet) 来关闭工作表并调用完成处理程序。

编辑:

我猜你的意思是这样的

...
self.window.beginSheet(progSheet) {(returnCode) -> Void in
progInd.stopAnimation(self)
progInd.indeterminate = true

}

progInd.startAnimation(self)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority,0)) {
self.readData(path) {
dispatch_async(dispatch_get_main_queue()) {
self.window.endSheet(progSheet)
}
}
}
}

func readData(path:String, completion: (() -> Void)) {
print("Hello!?")
completion()
}

关于Swift - 使用 performSelectorOnMainThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37248263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com