简体   繁体   中英

Swift: Populating numberOfSectionsInTableView and numberOfRowsInSection dynamically

I am trying to implement an iOS Table View in Swift that does the following:

  • Generates a number of sections by counting the number of objects currently stored in my Core Data entity
  • Create ONE ROW per section, each row representing/holding an object in my Core Data entity

Please forgive scrappy code, it needs tidying.

Here is my function for setting the number of sections. It simply returns the number of results fetched and provides this as my number of sections. Great.

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    let count = self.fetchedResultsController.fetchedObjects?.count
    if (count != 0){
    return count!        }
    else {
    return 0
    }
}

However I have no idea how to adapt the basic numberOfRowsInSection method included with the project file. It trips up on an NSRangeException for an array being beyond bounds of 0. I'm guessing this is the [section] array.

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let sectionInfo = self.fetchedResultsController.sections![section]
        return sectionInfo.numberOfObjects

}

Simply returning 1, for a single row per section which is what I want, does not work, falling on the same error above.

Can some kind coder please point me in the right direction.

Thanks!

Edit: The error occurs here whenever I return any numberOfSectionsInTableView greater than 1.

override func tableView(tableView: UITableView, numberOfRowsInSection section:    Int) -> Int {

   let sectionInfo = self.fetchedResultsController.sections![section]
   return sectionInfo.numberOfObjects

}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return self.fetchedResultsController.sections!.count
}

Here you return the number of sections, not the number of rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM