Append object to a variable

后端 未结 1 2026
甜味超标
甜味超标 2021-01-28 08:25

I\'m trying to append an object to an array of objects.

var products: [Product] = []

init() {
    Alamofire.request(.GET, Urls.menu).responseJSON { request in
          


        
1条回答
  •  逝去的感伤
    2021-01-28 09:09

    "Networking in Alamofire is done asynchronously" says the API description meaning instead of waiting for response from the server, it calls the handler when response is received but in the meantime code execution continues no matter what. and when the handler is called, the response is accessible only in that handler:- "The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler"

    You can use high priority thread if you want the handler to have that priority. Here is how to do that:

    Alamofire.request(.GET, Urls.menu).responseJSON { request in
        if let json = request.result.value {    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
                let data = JSON(son)
                var product: [Products] = []
    
                for (_, subJson): (String, JSON) in data {
                    product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
    
                    print(product)
                }
                dispatch_async(dispatch_get_main_queue()) {
                    self.products += product //since product is an array itself (not array element)
                    //self.products.append(product)
                }
            }
        }
        self.products.append(Product(id: 1, name: "test", description: "description", price: 1.0))
    }
    

    0 讨论(0)
提交回复
热议问题