TableViewController中的表在接收数据之前填充

时间:2014-08-04 12:10:23

标签: ios swift afnetworking afnetworking-2

所以我正在使用AFNetworking 2.0向服务发送POST和GET请求。由于我在整个应用程序中使用它,因此我使用这两个函数创建了一个包装类:

    // An HTTP GET call
func get(urlString:String, body:AnyObject?, completion:(data:AnyObject?, error:NSError?, operation: AFHTTPRequestOperation) -> ())
{
    var operation = self.GET(urlString,
        parameters: body,
        success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
            completion(data: (responseObject), error: nil, operation: operation)
        },
        failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
            completion(data: nil, error: error, operation: operation)
        }
    )
}

// An HTTP POST call
func post(urlString: String, body: AnyObject?, completion:(data:AnyObject?, error:NSError?, operation: AFHTTPRequestOperation) -> ())
{
    var operation = self.POST(urlString,
        parameters: body,
        success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
            completion(data: (responseObject), error: nil, operation: operation)
        },
        failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
            completion(data: nil, error: error, operation: operation)
        }
    )
}

问题是当我在TableViewController中使用它们时。由于方法运行异步(我相信),因此在收到数据之前创建表。这是TVC:

class ShopViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

var stores = [PartnerStore]()

override func viewDidLoad() {

    super.viewDidLoad()
    self.loadStores()
    // Do any additional setup after loading the view, typically from a nib.
}

override func numberOfSectionsInTableView(tableView: UITableView!) -> Int
{
    return 3;
}

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
// placeholder value
    return 1;
}

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    var cell = tableView.dequeueReusableCellWithIdentifier("PartnerShopCell") as PartnerStoreTableViewCell

    cell.storeLogoImageView.image = UIImage();
    cell.storeNameLabel.text = self.stores[indexPath.row].name;

    return cell;

}

func loadStores()
{
    var networkManager:APIClient = APIClient.sharedInstance
    networkManager.get("partner_stores/", body: nil, completion:  {
        (data:AnyObject?, error:NSError?, operation: AFHTTPRequestOperation)  in

        self.stores = data as [PartnerStore]
        println("Data \(self.stores)");
        self.tableView.reloadData()
        if (!error) {

        } else {
            println(error)
            println (operation.response.statusCode)
        }

        });
}
}

当我运行应用程序时,我得到一个“数组索引超出范围”错误,因为在调用cellForRowAtIndexPath时,get调用尚未完成。

我在考虑使用GCD,但我不确定这是否会有所帮助。任何建议都会很好。

1 个答案:

答案 0 :(得分:3)

您收到错误Array index out of range,因为您硬编码了委托方法中的行数,它应该是您的datasource的计数,这样当下载为finsih并重新加载{{ 1}}数据计数因异步加载而更新:

tableView