需要从我的班级

时间:2016-01-26 18:05:48

标签: ios swift2

我有一个UIPickerView我想要填充一系列值。值数组来自我的一个类中的函数(使用json获取值然后将它们放入数组中)。数据被成功抓取,并添加到函数内部的数组中,但由于某种原因它没有返回。

这是我的班级:

class Supplier {

    var supplierId: Int
    var supplierName: String


    init(id: Int, name: String){
        supplierId = id
        supplierName = name
    }

    static func arrayOfSupplierNames() -> [String] {
        let urlString = Constants.Urls.Suppliers.List;
        let session = NSURLSession.sharedSession();
        let url = NSURL(string: urlString)!;
        var suppliers: Array<String> = []

        session.dataTaskWithURL(url) { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
            if let responseData = data {

                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>;

                    if let suppliersDictionary = json["suppliers"] as? [Dictionary<String, AnyObject>] {

                        for aSupplier in suppliersDictionary {

                            if let id = aSupplier["id"] as? Int, let name = aSupplier["supplierName"] as? String {
                                let supplier = Supplier(id: id, name: name)
                                suppliers.append(supplier.supplierName)
                            }

                        }
                    }
                }catch {
                    print("Could not serialize");
                }
            }
            }.resume()

        return suppliers
    }
}

这似乎有效,因为当我调试时,我可以看到添加到数组中的值。我的ViewController中有另一个函数运行此函数并将其添加到本地数组,但从函数返回的数组似乎没有添加到视图控制器中的数组中:

func populateSuppliersArray() {

        let sup:Array = Supplier.arrayOfSupplierNames()

        for s in sup {
            supplierArray.append(s) //supplierArray is at the top scope of view controller. 
        }
    }

我甚至将类函数设置为静态,因此我不必初始化类只是为了使用该函数。我不确定这是正确的方法。当我在调试时查看sup变量时,它的值为零。

1 个答案:

答案 0 :(得分:1)

在异步块内接收json数据。在resume上调用dataTaskWithURL后,您的函数就会返回。您应该将完成块作为参数传递给arrayOfSupplierNames,并将数组传递给该完成块。您可以像这样修改您的功能:

// take a completion block as an argument
func arrayOfSupplierNames(completion: (([String]) -> Void)) -> Void {
    let urlString = Constants.Urls.Suppliers.List;
    let session = NSURLSession.sharedSession();
    let url = NSURL(string: urlString)!;
    var suppliers: Array<String> = []

    session.dataTaskWithURL(url) { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
        if let responseData = data {

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>;

                if let suppliersDictionary = json["suppliers"] as? [Dictionary<String, AnyObject>] {

                    for aSupplier in suppliersDictionary {

                        if let id = aSupplier["id"] as? Int, let name = aSupplier["supplierName"] as? String {
                            let supplier = Supplier(id: id, name: name)
                            suppliers.append(supplier.supplierName)
                        }

                    }
                    completion(suppliers) // pass the array to completion block
                }
            }catch {
                print("Could not serialize");
            }
        }
        }.resume()
}

你会这样称呼它:

Supplier.arrayOfSupplierNames { (suppliers) -> Void in
    // use suppliers as appropriate
}

请注意,异步调用完成块(将来某个时间)。