0

我在一箇中心點(班級)工作,在那裏我的數據被請求和檢索。Swift - Grand Central Dispatch Class

這個類可以從任何觀點被稱爲:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let group = dispatch_group_create() 
    var data = RestApiManager(group) 
    dispatch_group_notify(group, dispatch_get_main_queue()) { 
     return data 
    } 
} 

class RestApiManager { 

    let user = "user" 
    let password = "password" 

    var result: JSON = [] 

    init(group) { 

     dispatch_group_enter(group) 
     Alamofire.request(.GET, "http://example.com/api/") 
      .authenticate(user: user, password: password) 
      .responseJSON { _, _, result in 
       switch result { 
       case .Success(let data): 
        self.result[] = JSON(data) 
       case .Failure(_, let error): 
        print("Request failed with error: \(error)") 
       } 
       dispatch_group_leave(group) 
     } 
    } 
} 

但初始化類時,它已經失敗。

任何人都可以幫助我設計一個合適的方式?

感謝和問候

回答

1
import XCPlayground 

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 

import Foundation 

class C { 
    var txt: String = "start" 
    init(group: dispatch_group_t) { 
     dispatch_group_enter(group) 
     print(txt) 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {() -> Void in 
      usleep(200000) 
      self.txt = "end" 
      print(self.txt) 
      dispatch_group_leave(group) 
     } 
    } 
} 

func f() { 
    let group = dispatch_group_create() 
    let c = C(group: group) 
    dispatch_group_notify(group, dispatch_get_main_queue()) {() -> Void in 
     print("notify: \(c) created") 
    } 
} 

f() 
print("continue running ...") 

這個工作對我來說沒有任何麻煩。你寫過 「但是初始化這個類時它已經失敗了。」 這意味着什麼?詳細解釋你的'失敗'... 順便說一下,我不明白你如何從組通知處理程序返回你的數據(返回數據)......(通常來自任何異步代碼)

相關問題