2016-08-22 9 views
0

私は素早く新しいですし、SQLデータベースのデータを使用して塗りつぶすテーブルを設定しました。スウィフトテーブルのインデックスが範囲外です

表ロードは罰金時折、それはエラーを与える:

"Fatal Error: Index out of range".

それはちょうど、すべての今、もう一度、すべての時間を発生しません。

また、parseからsqlおよびhttp要求を使用して移行しました。テーブルにデータを入力するとき、私はこれに対して正しいアプローチを取っていますか?

ご迷惑をおかけして申し訳ありません。

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





} 

答えて

1

こちらがお役に立てば幸いです。私はよりよいコードのためにいくつかの小さなものを変えました(半分はバイアスとみなされます)。私は問題は主にあなたがループ内でtableViewをリロードしていたと思う。この他のすべては、このケースを処理するためのほんの少し良い方法でした。私はすべてviewDidLoadに入れ、tableViewは空の入力prequelをデータの受信にロードさせました。私はこれがこのシナリオを扱うためのより標準的だと思います。他の助けが必要なら私に知らせてください。

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

問題がreloadData()へのお電話は、あなたがtableDatatableImagesを構築しているwhileループ内であるということです。 whileループの後に移動します。その時点で、両方の配列が完全に読み込まれます。

関連する問題