【发布时间】:2017-09-04 14:23:49
【问题描述】:
我最近创建了一个新的视图控制器,其中包含一个集合视图。我还必须拥有其他具有集合视图的视图控制器。
我面临的问题是我试图为新的集合视图使用重新加载功能,但它给出了错误:'fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)'
关于它为什么会出错,我最好的假设是新集合视图的设置与其他两个不同(.reloadData() 在其他两个中工作正常)。这是新集合视图上 viewDidLoad 的代码:
override func viewDidLoad() {
super.viewDidLoad()
//self.resultsColl.delegate = self
//self.resultsColl.dataSource = self
testHashAt = textFieldFHash.text!
}
我注释掉了委托和数据源行,因为这是主要错误。在另外两个视图控制器中,我有这两个功能,它们工作得很好,但是当我在新的集合视图中使用它们时,我得到了与 .reloadData() 相同的错误。
我认为这就是我不能使用 .reloadData() 函数的原因。我已将集合视图作为数据源和委托以及在类声明中添加到视图控制器:
class HashtagViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
也只是以防这是错误,这是我的 getData() 函数,下面是 cellForItemAt 和 numberOfItemsInSection 函数以及 viewWillAppear:
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
fetchRequest.predicate = NSPredicate.init(format: "hashtag = %@", testHashAt);
taskTwo = try context.fetch(fetchRequest)
}
catch {
print("Get Data failed")
}
// Fetches data.
}
还有 cellForItemAt 和 numberOfItemsInSection:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return taskTwo.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let taskTHash = taskTwo[indexPath.row]
let cellHash = collectionView.dequeueReusableCell(withReuseIdentifier: "nCell", for: indexPath) as! HashCollectionViewCell
if testHashAt == taskTHash.hashtag {
cellHash.labelFHash.text = taskTHash.name!
}
else {
print("blank cell?")
}
if cellHash.labelFHash.text == "" {
print("cell is nil")
}
cellHash.layer.cornerRadius = 25
return cellHash
}
和 viewWillAppear:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getData()
resultsColl.reloadData()
}
我不知道为什么这个集合视图不适用于 dataSource、delegate 和 reloadData()。我该如何解决这个问题?
【问题讨论】:
-
您能否说明您如何声明和初始化导致问题的集合视图?
-
首先找出导致错误的行。在 Swift 错误上设置断点,以便执行将在正确的位置停止。否则,请查看您在赋值中使用
!的任何地方并更改它,以便您测试该值,而不是告诉编译器假设它不是 nil。 -
@PhillipMills 我已经这样做了,尽管我注释掉了哪些行会导致问题。导致问题的行是 self.resultsColl.delegate/dataSource = self 行。 reloadData() 行也会导致问题,但我认为它与委托和数据源不工作是相互关联的。
-
@PhilippOtto 我不确定你的意思,你指的是如何使用 CoreData 导入集合视图中的项目或一般创建(拖放、集合视图单元格视图控制器等)。 )?
-
@Richard:不,我的意思是您声明和初始化变量 resultsColl 的行。正如您已经说过的,您通过界面构建器中的插座进行设置。您是否 100% 确定在设置 dataSource 和委托时设置了 resultsColl 而不是 nil?您是否将插座变量正确连接到情节提要项目?
标签: ios swift core-data uicollectionview