2017-08-02 60 views
0

陣列我有需要在另一個視圖控制器讀取NSObjects的陣列。不過,我不確定我應該爲其設置數據的級別。訪問在另一個視圖控制器

下面最好該屏幕截圖說明了什麼,我試圖做的。每個HomeController都有一個標題,成員列表,描述和插圖collectionview(黃色欄)。我需要收集視圖的單元數量等於成員的數量。 screenshot

我試着用慵懶的VAR創建插圖的CollectionView裏面HomeController的參考但得到了錯誤: fatal error: Index out of range

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

再次,這是從插圖的CollectionView

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 
} 
+0

'讓hc = HomeController()'創建一個HomeController的新實例。也許這不是你想要的?它不會給你當前的HomeController對象。所以這取決於你如何創建房間數組。 – ryantxr

+0

@ryantxr有道理。這可能是我得到索引超出範圍錯誤的原因。謝謝。 – Stefan

回答

0

您需要的細胞檢查你的陣列的數量,以防止死機Index out of range

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

這到底是什麼? – Stefan

+0

只是爲了避免您的崩潰 –

0

你能調試及以下兩件事情份額則我們可以進一步看這個

  • 檢查什麼你得到
  • 檢查索引路徑,如果你的陣列有數據
+0

檢查'讓房間= homeController.rooms [indexPath.row]'有兩個指標。兩者均返回零值。 – Stefan

+0

這意味着該陣列不具有任何數據。所以現在下一步我們需要真正調試在HomeController中如何初始化數組。正如你在這裏創建一個新實例來獲取數組數據。 – Joe

+0

我包含的功能是在編輯後創建數組 – Stefan

相關問題