ios - 后台线程更新变量并导致索引越界 swift ios

标签 ios swift asynchronous indexoutofboundsexception

我有一个文本字段,每次用户在文本字段中键入新字符时,它都会执行服务器请求,并向用户动态显示搜索结果。这些存储在 search_results 数组中。我还在数组上运行以下代码行以确定是否有任何值出现两次。

let duplicate_array = (search_results.filter{ $0.name == search_results[indexPath.row].name })

问题是,如果我输入得足够快,search_results 数组就会从后台线程更新,并且我会在此代码上收到 indexOutOfBounds 异常,因为 indexPath.row 不再适合更新后的 search_results 的大小。有什么方法可以防止这种情况发生,我已经延迟了搜索查询的执行,以便最多每 0.3 秒执行一次,而不是更频繁,但是如果 search_results 大小很大。

最佳答案

正如您所解释的,索引越界是由于 indexPath.row 不再适合更新的 search_results 的大小造成的。

您可以通过检查 search_results.count 是否大于 indexPath.row 来防止这种情况发生。如果它不大于 indexPath.row,则触发结果重新加载,例如,如果您使用的是 UICollectionView,则通过调用 collectionView.reloadData()。 (无需访问 search_results[indexPath.row]

关于ios - 后台线程更新变量并导致索引越界 swift ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287548/

相关文章:

iphone - 在多个源代码中将 ObjC 和 C++ 与 C++ 模板类混合

ios - 使用后从overlay UIView转发触摸事件到下方的UIScrollView

ios - 用于匹配字符串子串的 Swift switch 语句

node.js - Node-Webkit 中的 NodeJs Async.waterfall

c# - 更新 Task 中的 UI 控件

android - 使用 splashscreen 插件为 cordova 创建的启动画面不会出现在 Visual Studio 2015 中

ios - cordova-plugin-camera:IOS 设备上出现崩溃错误 “No Image Selected”

iphone - 以编程方式捕获屏幕视频

iphone - 将数据从 Apple Watch 共享到 iPhone

multithreading - Node 线程是否是模拟循环的错误位置?