2015-12-21 20 views
-2

我想在完成一个方法时执行一个动作,在其他方法中执行一个方法,并且希望第二个方法停止,直到完成第一个方法。在Swift中完成方法时执行一个动作

我有一个方法:

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 

} 
+1

测试显示一些代码,使您的问题更好理解的。现在我误会了你或者解决方法只是在方法之后调用方法! – luk2302

+0

将代码放在方法的末尾。 – dasdom

+0

从第一种方法的最后一行调用第二种方法。 –

回答

5

这是你将如何实现这一目标:

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() 
} 
+0

代码是如何异步运行的。 – Juan

+1

我的例子中没有看到任何异步代码?如果你想使用异步代码,那么你将需要使用闭包来等待异步代码完成。如果你想要一个同步的例子,那么请更新你的问题,我很乐意修改我的答案。 – Swinny89

+0

代码“instanceOfCustomObject.obtenerExistenciaUsuario()”在Objective-C中运行异步方法。 – Juan

1

使用闭:

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() 
} 


} 
+0

我把它放在我的应用程序中,不要运行。 – Juan

相关问题