2

i have an array of model class and this model class have an array . i want to populate tableview from array . its showing me error

Here is my Model class

class DataModel {

    var name:[String]

    init(name:[String]) {
        self.name = name
    }
} 

Here is my model object :

class Data {
    static var product = [DataModel]()
}

Here is my function for append data to object :

class Function {

    static func read(compleationHandler:@escaping ()->()) {

        var model = ["nsu","iUB","UIU"]
        DispatchQueue.global(qos: .userInteractive).async {
            if Data.product.count == 0 {
                Data.product.append(DataModel(name: model))
            }
            DispatchQueue.main.async {
                compleationHandler()
            }
        }
    }
}

and here is my tableView Cell method :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell

        cell.textLabel?.text = Data.product[indexPath.row].name[indexPath.count]

        return cell
    }

Here is my ViewDidLoad :

myTableView.delegate = self
        myTableView.dataSource = self
        Function.read { [weak self] in
            print(Data.product.count)
            self?.myTableView.reloadData()
        }

    }
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
Ekramul Hoque
  • 672
  • 4
  • 17

1 Answers1

3

The problem probably is the way your delegates are set up. This is what i feel is what you are trying to achieve.

func numberOfSections(in tableView: UITableView) -> Int {
    return Data.product.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Data.product[section].name.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell

    cell.textLabel?.text = Data.product[indexPath.section].name[indexPath.row]

    return cell
}
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
  • Thank you its working but If i populate in one section how its possible ? – Ekramul Hoque Aug 23 '18 at 06:15
  • You have to map all the names to a one dimensional array and use that as data source. Also return 1 in numberOfSections. You can refer this to get an understanding of how to flatter multi dimensional arrays - https://stackoverflow.com/questions/24465281/flatten-a-array-of-arrays-in-swift – Rakesha Shastri Aug 23 '18 at 06:16