如何消除导致此线程1的错误:EXC_BAD_ACCESS错误?

时间:2017-08-09 12:45:57

标签: swift xcode debugging uicollectionviewcell exc-bad-access

我对Swift相当新(我在一个月前学会了它),我正在创建一个自定义集合视图单元,我将自定义类连接到View Controller类。我问这个问题是因为我一直在努力解决这个问题

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let answer = collectionView.numberOfItems(inSection: cellArray.count)

        return answer
}

出了好几个小时。此错误是我的View Controller类中的一个方法,它在LLDB窗口中显示错误消息“Thread 1:EXC_BAD_ACCESS(code = 2 ... [此处的计算机内存地址]”在let answer = collectionView.numberOfItems(inSection: cellArray.count)突出显示我有followed this tutorial然而这个错误并没有消灭。

我已经包含了我的View Controller类的一部分,我在其中初始化属性,如果这有用的话:

@IBOutlet weak var ibCollectionView: UICollectionView!

var cellArray:[customCollectionViewCell] = Array(repeatElement(customCollectionViewCell(), count: 6))

let displayedCellDimensions = CGSize(width: 343, height: 248)

LLDB界面的屏幕截图: Here is a screenshot of the LLDB interface.

感谢任何帮助,因为我非常困难。谢谢!

1 个答案:

答案 0 :(得分:1)

首先突然出现的是你以递归方式调用numberOfItemsInSection:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    let answer = collectionView.numberOfItems(inSection: cellArray.count)

    return answer

相反,你应该给它想要的东西,物品的数量:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return cellArray.count

当您在swift文件中重命名或删除并重新添加InterfaceBuilder插座而不修改故事板插座时,会出现处理collectionViews和tableViews的另一个问题。我已经包含了截图,因此您可以看到我的意思:

Storyboard, assistant editor, and connections inspector

如果其中一个圆圈为空,则连接断开。解决这个问题:

  1. 打开故事板并在heirarchy中选择集合视图。
  2. CTRL +从heirarchy拖动到助手编辑器中的swift文件(使用热键ALT + CMD + Enter打开)
  3. 应该出现对话。输入插座的设置。
  4. 清除swift文件和连接编辑器中的所有旧插座和断开的连接。