Reputation: 133
I have some problems that require a solution which is beyond my knowledge unfortunately at the moment. I perform a fetch request that returns an array of Floors entity object which has 2 attributes (floor number and number of rooms). I want to make a table with the number of sections corresponding the num of floors and the num. of rows in each section corresponding to the number of rooms per floor. I use a struct and 2 for in loops to separate the attributes for the table. The result is baffling me: if i declare one floor it works and a picker in the next vc displays floor "0". If I assign 2 rooms to it I get a giant print response and a table with 10s of rows. Please have a look at the code below and the pictures provided and if someone could help I would be thankful.
class RoomAndAlarmTypeTableVC: UITableViewController, NSFetchedResultsControllerDelegate {
//MARK: - Properties
private var managedObjectContext: NSManagedObjectContext!
private var storedFloors = [Floors]()
private var resultsArray = [Results]()
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
loadFloorData()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadFloorData() {
let floorRequest: NSFetchRequest<Floors> = Floors.fetchRequest()
do {
storedFloors = try managedObjectContext.fetch(floorRequest)
// tableView.reloadData()
print("\(storedFloors)")
} catch {
print("could not load data from core \(error.localizedDescription)")
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return resultsArray.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsArray[section].sectionObjects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "house cell", for: indexPath) as! ViewRooomNumberCell
cell.floorNumberTxt.text = String(storedFloors[indexPath.section].floorNumber)
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return resultsArray[section].sectionName
}
}
[![enter image description here][1]][1]
[![enter image description here][2]][2]
Upvotes: 0
Views: 53
Reputation: 8563
storedFloors
is an array of managedObjects, which already has all the information that you need. The number of sections is storedFloors.count
and the number of rows is storedFloors[sectionIndex].numberOfRooms
. To build a cell the floor is storedFloors[indexPath.section].floorNumber and the room number is simply indexPath.row
.
The other objects you created are wrong and confusing and should be removed.
Upvotes: 1