本文介绍了闭包外快速访问数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS的新手.我有一个疑问,我们如何才能在闭包内部访问数据或变量.以下是我的代码段.

I am newbie to iOS. I have query that how can we access data or variables inside closure. Following is my code snippet.

self.fetchData() { data in
       dispatch_async(dispatch_get_main_queue()) {
            println("Finished request")
            if let data = data { // unwrap your data (!= nil)
            let myResponseStr = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

            }
        }
    }      

我想将myResponseStr带到外面,例如 self.myString = myResponseStr

I want to get myResponseStr outside, like self.myString=myResponseStr

推荐答案

您应在调用fetchData的函数中使用完成处理程序闭包,例如:

You should employ completion handler closure in the function that calls fetchData, e.g.:

func fetchString(completionHandler: (String?) -> ()) {
    self.fetchData() { responseData in
        dispatch_async(dispatch_get_main_queue()) {
            println("Finished request")
            if let data = responseData { // unwrap your data (!= nil)
                let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
                completionHandler(responseString)
            } else {
                completionHandler(nil)
            }
        }
    }      
}

您会这样称呼它:

fetchString() { responseString in
    // use `responseString` here, e.g. update UI and or model here

    self.myString = responseString
}

// but not here, because the above runs asynchronously

这篇关于闭包外快速访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 22:21