索引 0 越界(必须小于 0)通过 segue 传递领域对象时出错



我有一个collectionViewController和detailViewController。我需要通过 segue 将对象从 CVController 传递到详细控制器。 下面是类 im 传递的对象:

class FilmCategory: Object {
@objc dynamic var id = 0
@objc dynamic var name = ""
var films = List<Film>() 
override static func primaryKey() -> String? {
return "id"
}

这是电影课:

class Film: Object {
@objc dynamic var id = 0
@objc dynamic var name = ""
var actors = List<String>()
@objc dynamic var imageURL = ""
@objc dynamic var duration = 0

override static func primaryKey() -> String? {
return "id"
}

PS:我从JSON初始化对象,一切正常, 在我的收藏中查看控制器我检索电影类别,如下所示:

class CategoriesViewController: UICollectionViewController {
let realm = try! Realm()
let serializer = JSONSerializer()
var filmCategories: Results<FilmCategory>?

override func viewDidLoad() {
super.viewDidLoad()
registerCellWithNib()
serializer.serialize(input: URLs.jsonCategoriesURL)
filmCategories = realm.objects(FilmCategory.self).sorted(byKeyPath: "id",ascending: true)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let categories = filmCategories {
return categories.count
} else {
return 0
}
}

我没有在方法中包含一行的单元格,因为所有内容都在 collectionView 中正确加载,但是当我单击单元格并执行 segue 时,我接收索引越界错误:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: SegueIdentifiers.selectCategory, sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifiers.selectCategory , let CategoryIndex = sender as? IndexPath, let filmCategories = filmCategories {
if let controller = segue.destination as? FilmsViewController {
controller.currentCategoryIndex = CategoryIndex.row
controller.category = filmCategories[CategoryIndex.row]
}
}
}
}

以下是我的详细信息视图控制器类的简要说明:

class FilmsViewController: UIViewController {
let realm = try! Realm()
var currentCategoryIndex = Int()
@objc dynamic var category: FilmCategory?

每次我执行 segue时,我都会收到错误,可能是通过 segue 传递类别的错误方式。我应该在查询之后发送它的索引吗?

prepare(for seque: sender:)中的sender将是UICollectionViewCell的实例(不是索引路径(。您可能希望获取对集合视图本身的引用。它的indexPathsForSelectedItems属性将为您提供所需的部分和行数据。

最新更新