2017-07-14 51 views
1

我有第一執行的主視圖控制器,其看起來像下面,夫特UICollectionView - 添加/移除數據從另一個類

MainViewController

class MainViewController: UIViewController { 
    var collectionView: UICollectionView! 
    var dataSource: DataSource! 

    SomeAction().call() { 
    self.dataSource.insert(message: result!, index: 0) 
    } 
} 

數據源的的CollectionView的

class DataSource: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 

    var conversation: [messageWrapper] = [] 

    override init() { 
     super.init() 
    } 

    public func insert(message: messageWrapper, index: Int) { 
     self.conversation.insert(message, at: index) 
    } 

    func numberOfSections(in collectionView: UICollectionView) -> Int { 
     return 1 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return conversation.count 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let textViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "textViewCell", for: indexPath) as! TextCollectionViewCell 
     let description = conversation[indexPath.row].description   
     textViewCell.textView.text = description 

     return textViewCell 
    } 
} 

因此,當執行MainViewController時,一個添加到collectionview的數據源中,它工作得很好。

問題 現在,我有另一個類,看起來像 SomeController

open class SomeController { 
    let dataSource: DataSource = DataSource() 

    public func createEvent() { 
     self.dataSource.insert(message: result!, index: 1) 
    } 
} 

當我從上面的控制器添加一些數據,該conversation是空的不具有現有一個記錄並拋出Error: Array index out of range。我可以理解,這是因爲我再次實例化了DataSource

  1. 如何添加/刪除其他類的數據?
  2. 這是最好的做法嗎?
  3. 我可以使對話成爲全局變量嗎?

回答

0

數據源類已重新初始化爲默認的nil值,您必須將更新的類傳遞給下一個控制器以訪問其更新的狀態。

  1. 如何添加/刪除其他類的數據?您的ViewController類的NSObject {

  2. 而您的收藏視圖代表:

    • 您應該使用類數據源。
    • 通過內部prepareForSegue您的數據源
  3. 是否做到這一點的最佳做法?

  4. 我可以讓談話爲全局變量?不,最好使用模型/ mvc風格。您的模型上的數據,您的視圖控制器上的ui。

+0

我不使用故事板,我還可以使用'prepareForSegue'還是有其他選擇? – moustacheman

0

看來你的初始數量爲1,但你在索引1插入(出指數) 使用self.dataSource.insert(message: result!, index: 0) insteaded

或者使用append

+0

它沒有工作! – moustacheman

+0

仍然'錯誤:數組索引超出範圍'? – Codus

相關問題