制作Onboarding Slide时遇数组越界崩溃:index 0超出空数组范围
解决引导页(Onboarding Slide)数组越界崩溃问题
问题分析
崩溃报错为-[__NSArrayI_Transfer objectAtIndex:]: index 0 beyond bounds for empty array,触发代码行:
var minItem: NSIndexPath = visibleItems.object(at: 0) as! NSIndexPath
核心原因是点击Next按钮时,CollectionView的可见项数组visibleItems为空,直接访问索引0导致越界。而visibleItems为空是因为引导页数据sliderArr通过异步API获取,数据尚未返回或加载失败时,CollectionView没有可显示的内容,自然不存在可见项。
解决方案
安全访问数组元素
先校验visibleItems是否为空,同时用可选绑定替代强制类型转换,避免双重隐患:guard let visibleIndexPaths = collectionView.indexPathsForVisibleItems as? [NSIndexPath], !visibleIndexPaths.isEmpty else { // 处理空数组场景:比如提示数据加载中,或直接终止后续逻辑 return } let minItem = visibleIndexPaths[0]控制Next按钮可用性
初始化时将Next按钮置灰禁用,直到异步API请求完成并刷新CollectionView后再启用按钮,从源头避免无效点击:// 初始化时 nextButton.isEnabled = false // 异步API请求回调 func loadOnboardingData() { URLSession.shared.dataTask(with: requestUrl) { [weak self] data, _, error in guard let self = self, let data = data, error == nil else { return } // 解析数据到sliderArr self.sliderArr = self.parseSliderData(from: data) DispatchQueue.main.async { self.collectionView.reloadData() self.nextButton.isEnabled = !self.sliderArr.isEmpty } }.resume() }处理无数据场景
当API返回空数据或请求失败时,显示空状态UI,同时保持Next按钮禁用,避免用户误操作:func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let itemCount = sliderArr.count if itemCount == 0 { // 显示空状态提示,比如"暂无引导内容" emptyStateLabel.isHidden = false nextButton.isEnabled = false } else { emptyStateLabel.isHidden = true nextButton.isEnabled = true } return itemCount }
内容的提问来源于stack exchange,提问作者Ahmed Darwish
相关产品推荐
相关产品推荐

