2017-04-11 82 views
1

我知道有这样的问题,但它不能像我在Swift 2中那样工作。我希望有人能澄清,这样我就可以像过去那样运作!我在Swift 2有这个代码,它会检测到变化firebase,更新表中的数据,然后重新加载只改变了指数:dispatch_get_main_queue在Swift 3中不能正常工作

DataService.ds.REF_USERS.observeEventType(.ChildChanged, withBlock :{ 
     (snapshot) in 
     if initialUserLoad == false { 
      for (index,user) in self.usersArray.enumerate() { 
       if user.objectForKey("uId") as! String == snapshot.key { 
        self.usersArray[index] = snapshot.value as! NSDictionary 
        dispatch_async(dispatch_get_main_queue()){[unowned self] in 
         self.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)]) 
        } 
       } 
      } 
     } 
}) 

Swift 3代码自动更新它改成这样:

DataService.ds.REF_USERS.observe(.childChanged, with :{ 
     (snapshot) in 
     if initialUserLoad == false { 
      for (index,user) in self.usersArray.enumerated() { 
       if user.object(forKey: "uId") as! String == snapshot.key { 
        self.usersArray[index] = snapshot.value as! NSDictionary 
        DispatchQueue.main.async{[unowned self] in 
         self.collectionView.reloadItems(at: [IndexPath(item: index, section: 0)]) 
        } 
       } 
      } 
     } 
}) 

现在我得到的错误是:

终止应用程序由于未捕获的异常“NSInternalInconsistencyException”,理由是:“尝试删除伊特从第0部分,其中只包含3个项目更新'

因此,似乎有一个线程问题。任何人都知道我可以如何使它像以前一样工作?预先感谢您提供的任何帮助。

+0

这不是一个线程问题。很显然,错误地给出了“理由:”试图从第0节中删除第4项,它只包含更新前的3个项目“。您正尝试删除比该部分中的总项目更大的索引处的项目。 –

+0

你检查了堆栈跟踪吗?哪条线路崩溃?设置异常断点 – Paulw11

+0

尝试重新加载单元时崩溃 –

回答

1

这不是任何线程问题,它与您的数据源有关。您的数据源不会相应更新。您应该在重新加载UICollectionView之前检查您的数据源,因为您没有重新加载UICollectionView只是reloadItemsAtIndexPaths:并且由于数据项计数不匹配,它会发生。