我试图使用– 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以外的值。在目标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()
}

09-11 19:45