将对象追加到变量 [英] Append object to a variable

查看:87
本文介绍了将对象追加到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将对象附加到对象数组。

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

我正在通过我的JSON响应循环并创建Product对象,但是当我尝试追加到product变量时,它没有不附加。

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.

这是输出:

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

第一行代表 print(self.products),其余为打印(产品)

谢谢

推荐答案

Alamofire中的网络异步完成说API描述意味着不是等待来自服务器的响应,而是在收到响应时调用处理程序,但同时代码执行继续,无论如何。当调用处理程序时,只能在该处理程序中访问响应: - 请求的结果仅在响应处理程序的范围内可用。任何依赖于响应的执行或从服务器接收的数据必须在处理程序

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

这篇关于将对象追加到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆