2017-04-23 55 views
1

我正在Swift中編寫iOS應用程序。在iOS的tableView中插入新行

每次頁面加載時,都會從服務器獲取電影列表,並將該列表填入tableView

我編寫了從靜態庫(Objective-C)中的服務器獲取JSON的代碼,並且通過通知設計模式接收json到應用程序。

override func viewDidLoad() { 
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(ReceivedNListOfMoviesNotification(_:)), name: Notification.Name(VUSDK.basicNotificationName()), object: nil) 
    requestForData() 
    } 

    func ReceivedNListOfMoviesNotification(_ notification:NSNotification) 
    { 
     if let info = notification.userInfo {   
     basicArray=info["Search"] as! [Any] 
     if basicArray.count>0 { 
      tableView.beginUpdates() 
      self.tableView.insertRows(at: [IndexPath.init(row: self.basicArray.count-1, section: 0)], with: .automatic)      
      tableView.endUpdates() 
     } 
     } 
    } 

但應用程序崩潰:

***斷言失敗 - [UITableView的_endCellAnimationsWithContext:],/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit- 3600.7.47/UITableView.m:1737 2017-04-23 13:49:12.562 VUDemo [4835:164247] ***由於未捕獲異常'NSInternalInconsistencyException',原因:'無效更新:無效的行數部分0.更新(10)後,現有節中包含的行數必須等於更新前該節中包含的行數(0),加上或減去(插入1個,刪除0個),加上或減去移入或移出該部分的行數(0移入,0移出)。

+0

你在哪裏添加數據源數組中的相應項目?您有**第一個**將項插入到數據源數組中,然後**然後**插入該行。 Btw:刪除'begin-/endUpdates'行。他們沒有效果。 – vadian

+0

basicArray = info [「Search」] as! [Any] –

+0

在這種情況下,不要調用'insert ...'。改爲調用'tableView.reloadData()'。 – vadian

回答

0

更換

if basicArray.count>0 { 
     tableView.beginUpdates() 

     self.tableView.insertRows(at: [IndexPath.init(row: self.basicArray.count-1, section: 0)], with: .automatic) 

     tableView.endUpdates() 
    } 

if !basicArray.isEmpty { 
     tableView.reloadData() 
    } 

,因爲要覆蓋整個陣列,而不是添加單個項目。