【问题标题】:Do one action when method is finished in Swift在 Swift 中完成方法时执行一项操作
【发布时间】:2015-12-21 10:48:08
【问题描述】:

我想在一个方法完成时执行一个操作,我在另一个方法中执行一个方法,我希望第二个方法停止,直到第一个方法完成。

我有那个方法:

func ejecutarOBJC(){
    let txtNombre = self.view.viewWithTag(4) as? UITextField
    let textoNombre=txtNombre?.text
    let txtContra = self.view.viewWithTag(5) as? UITextField
    let textoContra=txtContra?.text


    let instanceOfCustomObject: SQLViewController =  SQLViewController()
    instanceOfCustomObject.nombre = textoNombre;
    instanceOfCustomObject.contra = textoContra;
    instanceOfCustomObject.obtenerExistenciaUsuario()

}

还有另一种方法:

func otherMethod(){

    ejecutarOBJC()

//I want continue with that method when the execution of the other method finish

}

【问题讨论】:

  • 显示一些代码以使您的问题更容易理解。现在我要么误解了你,要么解决方案就是一个接一个地调用方法!?
  • 将代码放在方法的末尾。
  • 从第一个方法的最后一行调用第二个方法。
  • 那么问题出在哪里?部分代码是异步的吗?
  • 是的,第一种方法具有异步代码,我想停止应用程序直到代码完成,代码也是异步的。 @luk2302

标签: ios iphone swift ipad ios9


【解决方案1】:

这就是你实现这一目标的方法:

func methodOne() {

    //Method one code here

    methodTwo()

}

func methodTwo() {

    //Method Two code here.

}

根据您的评论,以下是使用异步代码时的等待方式:

func methodOne() {
    //Code goes here
    methodTwo { () -> () in
        //Method two has finished
    }
}

func methodTwo(completion: () -> ()) {
    //Code goes here
    completion()
}

【讨论】:

  • 我在您的示例中没有看到任何异步代码?如果要使用异步代码,则需要使用闭包来等待异步代码完成。如果您想要一个同步示例,请更新您的问题以适合,我很乐意修改我的答案。
  • 代码“instanceOfCustomObject.obtenerExistenciaUsuario()”在 Objective-C 中运行异步方法。
  • 检查我答案的第二部分,需要使用闭包。您可以在 Objective C 方法中返回一个块,并通过在 swift 中使用闭包,您将能够在该块/闭包中执行代码
【解决方案2】:

使用闭包:

func callCompetionFunction()
{
    // Tira mola meseda (do your stuff)

    completionFunction("a parameter") { () -> Void in
        print("function copleted")
    }
}

func completionFunction(param: AnyObject, completion: ()->Void)
{
    // Do your stuff

    completion()
}

在视图控制器中测试它

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    callCompetionFunction()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func callCompetionFunction()
{
    // Tira mola meseda (do your stuff)
    print("do something here")

    completionFunction("a parameter") { () -> Void in
        print("function copleted")
    }
}

func completionFunction(param: AnyObject, completion: ()->Void)
{
    // Do your stuff
    if param is String
    {
        print("parameter = \(param)")
    }

    print("going to execute completion closure")
    completion()
}


}

【讨论】:

  • 我把它放在我的应用程序中并且不运行。
猜你喜欢
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 2022-06-17
  • 1970-01-01
  • 2015-05-06
相关资源
最近更新 更多