2017-05-04 25 views
2

应用程序崩溃,并显示以下错误:加载tableview时出现错误“无效的更新:无效的部分数量”时,应用程序崩溃。

Invalid update: invalid number of sections. The number of sections contained in the table view after the update (6) must be equal to the number of sections contained in the table view before the update (3), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).' Please Help

我的代码:

func numberOfSections(in tableView: UITableView) -> Int { 

    return newsArray.count 

} 

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

    return 1 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


    let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as? NewsTableViewCell 


    cell?.contentView.backgroundColor = UIColor.clear 

    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 4, width: self.view.frame.size.width - 20, height: 410)) 

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9]) 
    whiteRoundedView.layer.masksToBounds = false 
    whiteRoundedView.layer.cornerRadius = 2.0 
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1) 
    whiteRoundedView.layer.shadowOpacity = 0.2 

    cell?.contentView.addSubview(whiteRoundedView) 
    cell?.contentView.sendSubview(toBack: whiteRoundedView) 

    let newsdata = newsArray[indexPath.section] 

    let date = NSDate(timeIntervalSince1970: TimeInterval(newsdata.meta)) 
    let dayTimePeriodFormatter = DateFormatter() 
    dayTimePeriodFormatter.dateFormat = "MMM dd YYYY " 

    let dateString = dayTimePeriodFormatter.string(from: date as Date) 


    print(dateString) 

    if let newsImg = self.newsImageCache.object(forKey: indexPath.section as AnyObject){ 
     cell?.imageOut.image = newsImg as? UIImage 
    } else { 
     loadImageFromWeb(uri: newsdata.photo, cache: self.newsImageCache, indexpath: indexPath) 

    } 
    cell?.titleLabel.text = newsdata.title 
    cell?.descLabel.text = newsdata.body 


    return cell! 
} 




func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 

    if indexPath.section + 3 == self.newsArray.count { 

     loadDatafromUrl() 
    } 
} 



func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 20 
} 

// Make the background color show through 
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let headerView = UIView() 
    headerView.backgroundColor = UIColor.clear 
    return headerView 
} 



func loadDatafromUrl(){ 
    let uri = "http://localhost/unani-info/admin/json/news.php" 
    print(uri) 
    if let url = URL(string: uri){ 

     let config = URLSessionConfiguration.default 
     config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData 
     let session = URLSession(configuration: config) 

     let task = session.dataTask(with: url, completionHandler: { 

      (rawData,response,error) in 

      if error != nil { 
       print("Couldnt load data") 
       print(error?.localizedDescription as Any) 

      } else { 
       if let data = rawData { 
        do{ 
         if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [AnyObject]{ 

          for index in 0...json.count-1 { 

           if let datas = json[index] as? [String: AnyObject] { 

            let newsObj = News() 
            newsObj.title = datas["title"] as! String 
            newsObj.body = datas["body"] as! String 
            let photo = datas["photo"] as! String 
            let photourl = "http://localhost/unani-info/admin/uploads/" + photo 
            newsObj.photo = photourl 
            newsObj.meta = datas["meta"] as! Int 

            self.newsArray.append(newsObj) 


           } 

          } 
          DispatchQueue.main.async { 
           self.tableView.reloadData() 
          } 

         } 
        }catch{ 
         print("error") 
        } 
       } 
      } 
     }) 
     task.resume() 
    } 

} 

回答

1

能不能请你:

DispatchQueue.main.async { 
    for index in 0...json.count-1 { 
     if let datas = json[index] as? [String: AnyObject] { 
      let newsObj = News() 
      newsObj.title = datas["title"] as! String 
      newsObj.body = datas["body"] as! String 
      let photo = datas["photo"] as! String 
      let photourl = "http://localhost/unani-info/admin/uploads/" + photo 
      newsObj.photo = photourl 
      newsObj.meta = datas["meta"] as! Int 
      self.newsArray.append(newsObj) 
     } 
    } 
    self.tableView.reloadData() 
} 

相反的:

for index in 0...json.count-1 { 
    if let datas = json[index] as? [String: AnyObject] { 
     let newsObj = News() 
     newsObj.title = datas["title"] as! String 
     newsObj.body = datas["body"] as! String 
     let photo = datas["photo"] as! String 
     let photourl = "http://localhost/unani-info/admin/uploads/" + photo 
     newsObj.photo = photourl 
     newsObj.meta = datas["meta"] as! Int 
     self.newsArray.append(newsObj) 
    } 
} 
DispatchQueue.main.async { 
    self.tableView.reloadData() 
} 
+0

谢谢你的回复,但它花费太多时间在tableview中加载数据。 –

+0

你能否建议一个适当的tableview分页方法..? –

+0

@YasheedMohammed恐怕我不能... – iWheelBuy

1

你正在反转numberOfSectionsnumberOfRowsInSection。你应该有:

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return newsArray.count 
} 
+0

它的bcz我需要一个表格单元格之间的空间。这就是为什么我喜欢这个 –

+0

,如果你需要tableViewCells之间的空间使用'tableView:heightForRowAtIndexPath:'获取更多细节请看https://developer.apple.com/reference/uikit/uitableviewdelegate/1614998-tableview?language=objc – pesch

+0

tableView:heightForRowAtIndexPath:,这是为了指定不同高度的行,不是吗?我没有任何细胞动态地改变它的高度。所有我需要提供像facebook新闻提要 –

相关问题