访问另一个视图控制器中的数组

时间:2017-08-02 00:37:16

标签: swift uicollectionview nsarray uicollectionviewcell

我有一个NSObject数组,我需要在另一个viewcontroller中读取。但是,我不确定应该为它设置数据的级别。

以下屏幕截图最能说明我尝试做的事情。每个HomeController都有一个标题,成员列表,描述和插入集合视图(黄色条)。我需要集合视图的单元格数量等于成员数量。 screenshot

我尝试使用lazy var在inset集合视图中创建对HomeController的引用,但是得到了错误: fatal error: Index out of range

lazy var homeController: HomeController = {
    let hc = HomeController()
    hc.liveCell = self
    return hc
}()

同样,这是从插图集合视图

中完成的
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath :
    IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: profileImageCellId, for: indexPath) as! profileImageCell

    let room = homeController.rooms[indexPath.row]

    print(room.members?.count)

    return cell

}

有什么建议吗?

修改

使用此函数将数据添加到数组

var rooms = [Room]()

func fetchAllRooms(){
    Database.database().reference().child("rooms").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let room = Room()

            room.rid = snapshot.key
            room.setValuesForKeys(dictionary)

            self.rooms.append(room)
            print(snapshot)

            DispatchQueue.main.async(execute: {
                self.collectionView?.reloadData()
            })
        }


        print("end of room snap")

    }, withCancel: nil)
}

以下是HomeController级别索引路径上项目的单元格

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    var cell = UICollectionViewCell()
    let section = indexPath.section

    let liveCell = collectionView.dequeueReusableCell(withReuseIdentifier: LiveCellId, for: indexPath) as! LiveCell

        let cell = liveCell

        let room = rooms[indexPath.row]

        liveCell.liveStreamNameLabel.text = room.groupChatName
        liveCell.descriptionLabel.text = room.groupChatDescription

        return cell
}

2 个答案:

答案 0 :(得分:0)

您需要检查数组的计数,以防止崩溃Index out of range

if homeController.rooms.count > indexPath.row {
  let room = homeController.rooms[indexPath.row]
  print(room.members?.count)
}

答案 1 :(得分:0)

你可以调试并分享以下两件事,然后我们可以进一步了解这个

  • 检查您获得的索引路径
  • 检查您的阵列是否有数据
相关问题