I'm in trouble with passing array data from one vc (which is table view controller, where I have news with come categories). I put these categories in array, then sort this array for unique elements, and this sorted array (which contains about 7 categories) I want to pass to another view controller.
What I have: I've created bar button item "Filter" and create an action for this button, called "filterButtonTapped". Inside action I've called method sorting array and called pushViewController
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//this is sortedArray
var categories: [String]?
//this is sorting method
func sortingArray() {
var arrayOfAllCategories = [""]
if let rssItems = rssItems {
for item in rssItems {
//print(item.category)
arrayOfAllCategories.append(item.category)
}
arrayOfAllCategories.remove(at: 0)
categories = arrayOfAllCategories.unique
}
}
}
//this is IBAction
@IBAction func filterButtonTapped(_ sender: UIBarButtonItem) {
sortingArray()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyboard.instantiateViewController(withIdentifier: "FilterViewController") as! FilterViewController
secondVC.arrayOfcategories = categories ?? [""]
self.navigationController?.pushViewController(secondVC, animated: true)
print("filter button tapped")
}
The problem is that in the second view controller this array of categories is appearing (I print it and see the result), but cells apparently dont see this data, because this table view is empty after launching app and also nothing happens when I tap the button:
class FilterViewController: UITableViewController {
var arrayOfcategories: [String]?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
print(arrayOfcategories) //this print prints array in the console
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayOfcategories?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) as! FilterCell
let category = arrayOfcategories?[indexPath.row]
cell.categoryLabel.text = category
return cell
}
}
What am I doing wrong? How pass this array and use it to fill cells?