Swift访问数据外部关闭

时间:2015-05-04 07:29:05

标签: ios swift

我是iOS的新手。我有问题,我们如何访问闭包内的数据或变量。以下是我的代码段。

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

1 个答案:

答案 0 :(得分:8)

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

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