2016-08-22 6 views
0

Ich bin neu bei swift und habe eine Tabelle eingerichtet, die Daten aus einer SQL-Datenbank ausfüllt.Swift-Tabellenindex außerhalb des Bereichs

Die Tabellenlasten in Ordnung, aber gelegentlich gibt es die Fehlermeldung:

"Fatal Error: Index out of range".

Es ist nicht die ganze Zeit nur hin und wieder passiert.

Auch ich habe migriert von Parse zu SQL und HTTP-Anfragen verwenden. Habe ich den richtigen Ansatz dafür gewählt, wenn ich die Daten in die Tabelle einfüge?

Jede Hilfe sehr geschätzt!

@IBOutlet var tableView: UITableView! 


    var tableData = [String]() 
    var tableImages = [String]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 


      } 



    override func viewDidAppear(animated: Bool) { 

     if Reachability.isConnectedToNetwork() == true { 

     self.tableView.hidden = true 

      self.tableData.removeAll(keepCapacity: true) 
     self.tableImages.removeAll(keepCapacity: true) 

     var nib = UINib(nibName: "vwTblCell3", bundle: nil) 
     tableView.registerNib(nib, forCellReuseIdentifier: "cell3") 


     let request = NSURLRequest(URL: NSURL(string: "********.php")!) 


     NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ 
      (response: NSURLResponse?, data: NSData?, error: NSError?)-> Void in 


      let str2 = String(data: data!, encoding: NSUTF8StringEncoding) 



      let str3 = Int(str2!)! 





      let url = NSURL(string: "********")! 

      let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in 

       if let urlContent = data { 



        do { 

         let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) 


         print(str3) 

         var i = 0 

         while i < str3 { 

         print(jsonResult[i]["title"]! as! String) 
          print(jsonResult[i]["image"]! as! String) 

          self.tableData.append(jsonResult[i]["title"]! as! String) 
          self.tableImages.append(jsonResult[i]["image"]! as! String) 

          i = i + 1 

          dispatch_async(dispatch_get_main_queue(), {() -> Void in 
           self.tableView.reloadData() 
          }) 

         } 

        } catch { 

         print("JSON serialization failed") 

        } 


       } 


      } 

      task.resume() 




      }); 


      print(tableData) 


      self.tableView.hidden = false 


     } 

    } 


    // 2 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 




     return self.tableData.count 
    } 


    // 3 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell  { 
     let cell: TblCell3 = self.tableView.dequeueReusableCellWithIdentifier("cell3") as! TblCell3 
     cell.lblAffiliate.text = tableData[indexPath.row] 


     let url3 = NSURL(string: "https://www.********.co.uk/\(tableImages[(indexPath as NSIndexPath).row]).png") 
     cell.affiliateImage.sd_setImageWithURL(url3) 


     return cell 
    } 

    // 4 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     print("Row \(indexPath.row) selected") 
    } 

    // 5 
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return 400 
    } 





} 

Antwort

1

Ich hoffe, das hilft. Ich habe ein paar Kleinigkeiten geändert, um einen besseren Code zu bekommen (die Hälfte könnte als Verzerrung betrachtet werden). Ich denke, das Problem ist meist, dass Sie die TableView in der Schleife neu laden. Alles andere war nur eine etwas bessere Art, mit diesem Fall umzugehen. Ich legte alles in viewDidLoad, und ließ die TableView leeren Eingang Prequel zum Empfangen von Daten. Ich denke, das ist mehr Standard für den Umgang mit diesem Szenario. Wenn Sie weitere Hilfe benötigen, lassen Sie es mich wissen.

class ViewController: UIViewController { 

    @IBOutlet var tableView: UITableView! 

    var tableData: [String] = [] 
    var tableImages: [String] = [] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     if Reachability.isConnectedToNetwork() == true { 
      var nib = UINib(nibName: "vwTblCell3", bundle: nil) 
      tableView.registerNib(nib, forCellReuseIdentifier: "cell3") 

      let request = NSURLRequest(URL: NSURL(string: "********.php")!) 

      NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ 
       (response: NSURLResponse?, data: NSData?, error: NSError?)-> Void in 

       let str2 = String(data: data!, encoding: NSUTF8StringEncoding) 
       let str3 = Int(str2!)! 
       let url = NSURL(string: "********")! 

       let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in 
        if let urlContent = data { 
         do { 
          let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) 
          self.tableData = [] 
          self.tableImages = [] 
          for i in 0..<str3 { 
           self.tableData.append(jsonResult[i]["title"]! as! String) 
           self.tableImages.append(jsonResult[i]["image"]! as! String) 
          } 

          dispatch_async(dispatch_get_main_queue()) { 
            self.tableView.reloadData() 
          } 
         } catch { 
          print("JSON serialization failed") 
         } 
        } 
       } 
       task.resume() 
      }); 
     } 
    } 

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell  { 
     let cell: TblCell3 = self.tableView.dequeueReusableCellWithIdentifier("cell3") as! TblCell3 
     cell.lblAffiliate.text = tableData[indexPath.row] 


     let url3 = NSURL(string: "https://www.********.co.uk/\(tableImages[(indexPath as NSIndexPath).row]).png") 
     cell.affiliateImage.sd_setImageWithURL(url3) 

     return cell 
    } 

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     print("Row \(indexPath.row) selected") 
    } 

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return 400 
    } 
} 
1

Das Problem ist, dass Ihr Anruf an reloadData() innerhalb der while Schleife ist, in dem Sie tableData und tableImages bauen. Verschieben Sie das nach der while-Schleife, wodurch beide dieser Arrays vollständig ausgefüllt werden.

Verwandte Themen