如何在执行另一个类方法代码后执行一些代码?

时间:2016-05-19 05:50:48

标签: ios swift

我有一个常见的Web服务类。在那个班级我写了方法getcitydetail()。我想在得到结果后填充那个城市细节。

我在viewDidload中编写了以下代码:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
   let objWebService = NTMWebServices()
    objWebService.getCityDetail()
}

执行getcitydetail后,我想在这里做一些操作。 我想我们可以在swift中使用闭包来做到这一点。但我并不知道如何使用它。

2 个答案:

答案 0 :(得分:0)

在这种情况下使用闭包尝试类似

func getCityDetail (completion:()->()){

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

        //background thread, do ws related stuff, the ws should block until finished here

        dispatch_async(dispatch_get_main_queue()) {
            completion() //main thread, handle completion
        }
    }
}

然后你可以像

一样使用它
objWebService.getCityDetail {
   //do something when the ws is complete
}

答案 1 :(得分:0)

您可以尝试以下任何一项:

  1. 如果getCityDetail()是异步请求,那么Use Delegate to respond with the result to the registered class。     例如:

    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error:
    

    NSError!) - >无效

        // Handle incoming data like you would in synchronous request
        var reply = NSString(data: data, encoding: NSUTF8StringEncoding)
        // Conform to the protocol with the results here
    })
    
  2. iOS Swift Pass Closure as Property? - 在这里你可以使用闭包作为属性,并且可以在类之间进行通信
相关问题