1

I have a main view controller executed first which looks something like below,

MainViewController

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

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

DataSource of the 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
    }
}

So, when the MainViewController is executed there is one added to the datasource of the collectionview which works perfectly fine.

Problem Now, I have another class which looks something like SomeController

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

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

When I add some data from the above controller, the conversation is empty which doesn't have the existing one record and throw Error: Array index out of range. I can understand that it is because I have again instantiated the DataSource.

  1. How to add/remove data from other class?
  2. Is it the best practice to do it?
  3. Can I make the conversation as global variable?
moustacheman
  • 1,424
  • 4
  • 21
  • 47

2 Answers2

0

The Datasource class had been re initialised with it's default nil value, you have to pass the updated class to the next controller to access its updated state.

  1. How to add/remove data from other class?

    • You should use class Datasource: NSObject {
    • And your collection view delegates on your viewcontroller class.
    • pass your dataSource inside prepareForSegue
  2. Is it the best practice to do it?

    • Yes
  3. Can I make the conversation as global variable? No, best to use models / mvc style. Data on your models, ui on your viewcontrollers.

0

It seems your initial count is 1 but you insert at index 1(out of index) Use self.dataSource.insert(message: result!, index: 0) insteaded

Or use append.

Codus
  • 1,433
  • 1
  • 14
  • 18