Swift:从dispatch_async内部返回结果

时间:2015-01-22 02:19:04

标签: swift grand-central-dispatch

所以我在这里有一段代码不起作用。这是因为它在尝试解包可选值时发现了nil。这是因为它在异步方法中被初始化。我的问题是,在取出结果之前,我该如何推迟返回函数?

struct Domain {
    var name: String?
    var tld: String?
    var combined: String {
        get {
            return self.name!+self.tld!
        }
    }
    var whoIs: String {
        get {
            if self.whoIs.isEmpty {
                var result: String?
                dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                    let whois_url = NSURL(string: SEARCH_URL+self.combined+"/whois")
                    result = NSString(contentsOfURL: whois_url!, encoding: NSUTF8StringEncoding, error: nil)
                    print(result!)
                })
                return result!
            }
            return self.whoIs
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您想等待阻止结果,只需将dispatch_async替换为dispatch_sync

dispatch_sync(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    let whois_url = NSURL(string: SEARCH_URL+self.combined+"/whois")
    result = NSString(contentsOfURL: whois_url!, encoding: NSUTF8StringEncoding, error: nil)
    print(result!)
})

这将确保在将URL的内容提取到结果中之前,方法不会返回。