Append object to a variable

☆樱花仙子☆ 提交于 2019-12-20 06:05:10

问题


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

var products: [Product] = []

init() {
    Alamofire.request(.GET, Urls.menu).responseJSON { request in
        if let json = request.result.value {
            let data = JSON(json)

            for (_, subJson): (String, JSON) in data {
                let product = Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)

                print(product)

                self.products.append(product)
            }
        }
    }

    self.products.append(Product(id: 1, name: "test", description: "description", price: 1.0))

    print(self.products)
}

I'm doing a loop through my JSON response and creating the Product object, but when I try to append to products variable, it doesn't append.

Here is the Output:

[Checkfood.Product]
Checkfood.Product
Checkfood.Product
Checkfood.Product
Checkfood.Product
Checkfood.Product

The first line represents the print(self.products) and the rest is print(product)

Thank you


回答1:


"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))
}


来源:https://stackoverflow.com/questions/33192206/append-object-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!