user8977455
user8977455

Reputation:

loading tableview from 2 different arrays

I have 2 coredata arrays. One has 3 elements and the other one also has 3 elements. Now I want to load in my tableview both these arrays. So I'll have a total of 6 rows in my tableview.

This I have achieved like so...

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let totalCount = (customerDetails.count) + (customerDetails2.count)
    return totalCount
}

And the data of these two arrays I tried loading like so in the cellForRowAt...

    let customers = customerDetails[indexPath.row]   //CRASHES HERE
    for i in 0..<(customerDetails.count) {
        cell.nameLabel.text = customers.fname
        if i == customerDetails.count {
            break
        }
    }
    let customers2 = customerDetails2[indexPath.row] 
    for i in 0..<(customerDetails2.count) {
        cell.nameLabel.text = customers2.fname
        if i == customerDetails2.count {
            break
        }
    }

But it crashes at the line mentioned saying Index out of range possibly because customerDetails has only 3 rows while the total cells loaded is 6.

What can be done in such a case..?

Upvotes: 6

Views: 2147

Answers (3)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Change code in cellforRow to this , note

 let arr1Count = customerDetails.count

  if(indexPath.row < = arr1Count )
 {
     let customers = customerDetails[indexPath.row]
      cell.nameLabel.text = customers.fname
 }
else

{
     let customers = customerDetails2[indexPath.row - arr1Count]
      cell.nameLabel.text = customers.fname

 }

Upvotes: 0

Agent Smith
Agent Smith

Reputation: 2913

Instead of creating it with only one section you can divide the both into two sections:

let sections = [customerDetails,customerDetails2]

and in numberOfSections you can provide count:

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

After that, In your numberOfItemsInSection you can provide the corresponding array according to the section number:

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

Once you've done this you can easily access provide your data to cellForRow like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let customer = sections[indexPath.section][indexPath.row]
     cell.nameLabel.text = customer.name
}

Hope it helps!!

Upvotes: 3

Nitish
Nitish

Reputation: 14113

if indexPath.row < customerDetails.count
{
    // load from customerDetails array
    let customer = customerDetails[indexPath.row]
}
else
{
   // load from customerDetails2 array
   let customer = customerDetails2[indexPath.row - customerDetails.count]
}

Upvotes: 4

Related Questions