ios - dispatch_get_main_queue 在 Swift 3 中不能正常工作

标签 ios swift multithreading firebase

我知道有这样的问题,但它并没有像我在 Swift 2 中那样工作。我希望有人能澄清一下,这样我就可以像以前一样工作了!我在 Swift 2 中有这段代码,它会检测到 firebase 中的变化,更新表中的数据,然后仅重新加载发生变化的索引:

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)])
                   }
               }
           }
       }
})

我现在得到的错误是:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 4 from section 0 which only contains 3 items before the update'

所以好像是线程的问题。任何人都知道我怎样才能让它像以前一样工作?提前感谢您提供的任何帮助。

最佳答案

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

关于ios - dispatch_get_main_queue 在 Swift 3 中不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339439/

相关文章:

c# - Parallel.ForEach错误

iphone - 在 iOS iPhone 模拟器上安装 TestFlight 应用程序 - 注册失败

javascript - 在Swift中使用JS隐藏WKWebView集合元素

iphone - MPMoviePlayerController - 控件未对齐

swift - App Store 更新会删除核心数据/NSUserDfeaults 吗?

c - posix 线程阻塞信号和解除阻塞

objective-c - 我的plist改变了,如何替换文档目录中改变的字符串

ios - 如何捕获 Swift 崩溃并进行一些日志记录

swift - NSTextList 格式

python - 当一个线程正在运行时阻塞其他线程