ios - 可能的竞争条件? Swift 2 iOS 应用程序随机不调用 func tableView(tableView

标签 ios json swift uitableview

我正在开发一个应用程序,它接受用户输入(8-10 位数字),并将其 POST 到 php 脚本,该脚本依次查询数据库并以 JSON 形式返回结果。

我解析 JSON 并将值保存到数组中,然后将这些数组加载到 tableView 中。

用户点击搜索,这会引入一个新 View 的segue(通过导航 Controller ),JSON数据被发送到 TableView ,在viewDidLoad()内部我解析JSON并将其保存在数组中,并在func中tableView 我将数组中的值读取到行中,然后返回单元格。

我的问题是,有时数据不会加载到行中,尽管数组总是被填充,但我得到一个空白的表格 View ,我单击返回并再次尝试搜索,并且它有效......几次然后随机停止。

我确实单击了 TableView 的委托(delegate)和数据源。我在 plist 中添加了 HTTP 异常。

这是我的第一个项目,因此感谢任何提示。我怀疑我的代码放置可能是导致竞争条件的问题?因为我在 viewDidLoad() 函数中解析 JSON?

代码:

import UIKit

class ResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


@IBOutlet weak var tableView: UITableView!

var ccnit = ""
var cunsArray : [String] = []
var accountsArray : [String] = []
var statusArray : [String] = []
var typesArray : [String] = []
var assignedArray : [String] = []



override func viewDidLoad() {
    super.viewDidLoad()


    //establish connection
    let url = NSURL(string: "http:IPADDRESS/App/query.php")
    let request = NSMutableURLRequest(URL:url!)
    request.HTTPMethod = "POST"

    request.HTTPBody = ccnit.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }
        //print("response = \(response)")

       // let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
        //print("responseString = \(responseString)")



        //parse JSON

        do {

            let jsonArray = try (NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)) as! NSArray

            //loop through json array and take out strings
            var counter = 0
            while counter < jsonArray.count{
                let cun = jsonArray[counter]["ticket_no"] as? String
                self.cunsArray.append(cun!)

                let account = jsonArray[counter]["accountname"] as? String
                self.accountsArray.append(account!)             

                let status = jsonArray[counter]["status"] as? String
                self.statusArray.append(status!)

                let type = jsonArray[counter]["category"] as? String
                self.typesArray.append(type!)

                let assigned_to = jsonArray[counter]["assigned_to"] as? String
                self.assignedArray.append(assigned_to!)

                counter = counter + 1
            }

            if (self.cunsArray.count > 0)
            {
                print("cunsArray has \(self.cunsArray.count) items")
            }
            if (self.accountsArray.count > 0)
            {
                print("accountsArray has \(self.accountsArray.count) items")
            }

            print("Finished populating arrays")
            self.tableView.delegate = self
            self.tableView.dataSource = self

        } catch let err {
            print(err)
        }

    }
    task.resume()


    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cunsArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
    //print("*****inside tableview func")
    print("returning cells")
    //  cell.account.text = ""
    cell.cun.text = cunsArray[indexPath.row]
    cell.account.text = accountsArray[indexPath.row]
    cell.status.text = statusArray[indexPath.row]
    cell.type.text = typesArray[indexPath.row]
    cell.assigned_to.text = assignedArray[indexPath.row] 

    return cell
}
}

最佳答案

看起来像是后台线程的问题:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request)

可能在内部后台线程上,然后您在同一线程上设置表数据源/委托(delegate)。

尝试交换:

        self.tableView.delegate = self
        self.tableView.dataSource = self

dispatch_async(dispatch_get_main_queue(), {() -> Void in
        self.tableView.delegate = self
        self.tableView.dataSource = self
 })

编辑:

Jeremy Herrero表示数据源/委托(delegate)可能已添加到 Storyboard级别,如果是这样,正确的解决方案是:

dispatch_async(dispatch_get_main_queue(), {() -> 中无效 self.tableView.reloadData() })

关于ios - 可能的竞争条件? Swift 2 iOS 应用程序随机不调用 func tableView(tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627311/

相关文章:

java - 带有 rest-plugin : Map JSON value to ENUM 的 Struts2

java - GSON从复杂的json中获取字符串

java - 使用 jackson jersey 将复杂的 hashmap 转换为 JSON

swift - 解决包依赖 swiftUI 项目时出错

ios - Lazy 关键字对内存或性能有害吗?

ios - 调整图像大小后检测公差颜色

ios - 如何以编程方式更改 iOS 键盘宽度?

ios - 使用默认对话框将图像上传到 Facebook

ios - 如何在iOS应用程序的默认文档目录中创建文件

ios - 调整导航 Controller 中自定义 UIBarButtonItem 的大小