macOS fatal error: Index out of range NSTableView - swift

I am developing a macOS application. i have a problem with a tableView that load an array of products from a web server. The products are correctly received by the app (i see them in console). But i have these problems:
1) i can't see my products text descriptions in my tableView cells;
2) when i click on a single cell the app crash with this error message:
fatal error: Index out of range
Here is my code:
import Cocoa
import AppKit
class Controller: NSViewController {
#IBOutlet var tableViewa: NSTableView!
var products = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Table list"
tableViewa.reloadData()
}
override func viewDidAppear() {
reload()
tableViewa.backgroundColor = NSColor.red
tableViewa.allowsEmptySelection = true
tableViewa.gridColor = NSColor.red
}
func reload() {
products = []
tableViewa.reloadData()
tableViewa.backgroundColor = NSColor.red
Products.store.requestProducts{success, products in
if success {
self.products = products!
self.tableViewa.reloadData()
}else {
print("download failed")
}
self.tableViewa.reloadData()
}
}
extension MasterViewController: NSTableViewDataSource, NSTableViewDelegate {
func numberOfRows(in atableView: NSTableView) -> Int {
print("products number: \(products.count)")
return products.count
}
func tableViewSelectionDidChange(_ notification: Notification) {
let tas = IndexPath(item: products.count, section: 0)
let Cell = tableViewa.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"),owner: tas ) as! ProductCell
let product = products[(tas as NSIndexPath).item]//here crash my app
Cell.product = product
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return true
}
func tableView(_ tableView: NSTableView, cellForRowAt indexPath: IndexPath) -> NSTableCellView{
let Cell = tableViewa.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"),owner: indexPath ) as! ProCell
let product = products[(indexPath as NSIndexPath).item]
Cell.product = product
Cell.textField?.stringValue = array.item.1
return Cell
}
}

How ya doing?
You can use the IndexPath init
init(row: Int, section: Int)
instead
init(item: Int, section: Int)
After that you recover the row that way
let product = products[(tas as NSIndexPath).row]
Explanation:
The item parameter is used to identify an item in a section from collection view and row to table view

Related

Bind UITableView with Combine DataSource

I want to directly link a UITableView with a #Published attribute without using DiffableDataSouce.
If I make the person
struct Person {
let name: String
}
and create the data array:
#Published
var people = [Person(name: "Kim"), Person(name: "Charles")]
So I want to bind my UITableView directly, with something like:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return $people.count()
}
But this gives the error
Cannot convert return expression of type 'Publishers.Count<Published[Person]>.Publisher>' to return type 'Int'
The problem here is that the UITableViewDataSource is pull based (the framework pulls data from your code) but Publishers are push based (they push data to something.) That means that in order to make it work, you need a Mediator (a la the Mediator pattern.)
One option would be to bring in RxSwift/RxCocoa and the RxCombine project to translate between Combine and RxSwift and use the functionality where this already exists. That's a lot for this one ask, but maybe you have other areas where RxCocoa could streamline your code as well.
For just this ask, here is a Mediator that I think would work:
#available(iOS 13.0, *)
final class ViewController: UIViewController {
var tableView: UITableView = UITableView()
#Published var people = [Person(name: "Kim"), Person(name: "Charles")]
var cancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableView)
cancellable = $people.sink(receiveValue: tableView.items { tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = item.name
return cell
})
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.people = [Person(name: "Mark"), Person(name: "Allison"), Person(name: "Harold")]
}
}
}
extension UITableView {
func items<Element>(_ builder: #escaping (UITableView, IndexPath, Element) -> UITableViewCell) -> ([Element]) -> Void {
let dataSource = CombineTableViewDataSource(builder: builder)
return { items in
dataSource.pushElements(items, to: self)
}
}
}
class CombineTableViewDataSource<Element>: NSObject, UITableViewDataSource {
let build: (UITableView, IndexPath, Element) -> UITableViewCell
var elements: [Element] = []
init(builder: #escaping (UITableView, IndexPath, Element) -> UITableViewCell) {
build = builder
super.init()
}
func pushElements(_ elements: [Element], to tableView: UITableView) {
tableView.dataSource = self
self.elements = elements
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
elements.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
build(tableView, indexPath, elements[indexPath.row])
}
}

ERROR: attempt to delete row 0 from section 1, but there are only 1 sections before the update (Swift and Realm)

So I'm fairly new to Realm and Swift and I'm currently building my first Gym App and I'm currently struggling with this error. I get this error each time I attempt to swipe to delete a row/section.
I think that I'm updating my Realm correctly, but apparently not because I keep getting the same error.
Any help or guidance would be much appreciated.
import UIKit
import RealmSwift
import SwipeCellKit
class WorkoutsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SwipeTableViewCellDelegate {
let realm = try! Realm()
var workouts : Results<Workouts>?
var days : Results<WeekDays>!
var daysOfWeek : [String] = ["Monday", "Tuesday", "Wednsday", "Thursday", "Friday", "Saturday", "Sunday"]
let picker = UIPickerView()
#IBOutlet weak var WorkoutsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
WorkoutsTableView.delegate = self
WorkoutsTableView.dataSource = self
picker.delegate = self
picker.dataSource = self
loadCategories()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.rowHeight = 80.0
//Populate based on the # of workouts in each day.
let day = days[section]
return day.workouts.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return days[section].day
}
func numberOfSections(in tableView: UITableView) -> Int {
return days.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell
cell.delegate = self
if (days?[indexPath.row]) != nil {
cell.accessoryType = .disclosureIndicator
//Populate with titles of workouts based on section/day of the week.
//cell.textLabel?.text = days?[indexPath.row].workouts[indexPath.row].name
cell.textLabel?.text = days[indexPath.section].workouts[indexPath.row].name
}
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
if let workoutForDeletion = self.days?[indexPath.row] {
do {
try self.realm.write {
self.realm.delete(workoutForDeletion)
}
} catch {
print("Error deleting workout, \(error)")
}
}
self.WorkoutsTableView.reloadData()
}
// customize the action appearance
deleteAction.image = UIImage(named: "delete-icon")
return [deleteAction]
}
func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
var options = SwipeOptions()
options.expansionStyle = .destructive
return options
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
#IBAction func AddWorkoutButton(_ sender: UIButton) {
var textField = UITextField()
let alert = UIAlertController(title: "New Workout", message: "Please name your workout...", preferredStyle: .alert)
let addAction = UIAlertAction(title: "Add Workout", style: .default) { (UIAlertAction) in
//Add workout to database
//Create a two dimensional array object in Realm with numbers corresponding to each day of the week.
//Append workouts to the day in the dictionary that the user selects.
let newWorkout = Workouts()
let dow = WeekDays()
dow.day = self.daysOfWeek[self.picker.selectedRow(inComponent: 0)]
newWorkout.name = textField.text!
dow.workouts.append(newWorkout)
self.save(newDay: dow)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Muscle Group"
textField = alertTextField
alertTextField.inputView = self.picker
}
alert.addAction(addAction)
present(alert, animated: true, completion: nil)
}
func save(newDay: WeekDays){
do {
try realm.write {
realm.add(newDay)
}
} catch {
print("Error saving workout \(error)")
}
WorkoutsTableView.reloadData()
}
func loadCategories(){
days = realm.objects(WeekDays.self)
WorkoutsTableView.reloadData()
}
#IBAction func EditWorkout(_ sender: UIBarButtonItem) {
}
}
extension WorkoutsViewController : UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 7
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return daysOfWeek[row]
}
}
class WeekDays : Object {
#objc dynamic var day : String = ""
let workouts = List<Workouts>()
}
class Workouts : Object {
#objc dynamic var name : String = ""
var parentDay = LinkingObjects(fromType: WeekDays.self, property: "workouts")
}
I think you're confusing the dereferencing of self.days. It looks like this is an array of days, each containing an array of workouts. This is supported by the cellForRowAt function operation for working out what is in each row:
cell.textLabel?.text = days[indexPath.section].workouts[indexPath.row].name
But for your deletion code you are dereferencing days only by the row number, i.e.:
if let workoutForDeletion = self.days?[indexPath.row] {
There is no use of indexPath.section there. Correcting that will help.
You may want to look into the usual code for deleting rows though, which is to use code similar to below:-
days[indexPath.section].remove(at: indexPath.row) // Make this a realm update though
tableView.deleteRows(at: [indexPath], with: .fade)
Which saves the complete reload of data and gives you a nicer UI update.

How to delete a cell in the tableview from another View controller?

I am trying to delete a cell in the tableview from another view controller. I have modeled my code similar to the question posted below but I still can't seem to successfully delete the selected row/cell in the CalorieVC when the delete button is pressed in the DeleteVC
Deleting a row of a tableview from another viewcontroller
SideNote: there is button in the cells to popup the DeleteVC, I am also getting an error upon pressing the the deleteBtn in the CalorieVC: DeleteRowInTableviewDelegate on let picked saying Thread 1: Fatal error: Index out of range
import UIKit
class CalorieViewController: UIViewController {
var selectedFood: FoodList! // allows data to be passed into the CalorieVC
var deleteItems: CalorieItem? // passes data to DeleteVC
// allows data to be sepearted into sections
var calorieItems: [CalorieItem] = []
var groupedCalorieItems: [String: [CalorieItem]] = [:]
var dateSectionTitle: [String] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
// Allows data in cells to seperate by section
groupedCalorieItems = Dictionary(grouping: calorieItems, by: {$0.foodList.date})
dateSectionTitle = groupedCalorieItems.map{$0.key}.sorted()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DeleteSegue" {
let vc: DeleteViewController = segue.destination as! DeleteViewController
vc.deleteItems = self.deleteItems
// vc.delegate = self
}
}
}
extension CalorieViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return dateSectionTitle.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let date = dateSectionTitle[section]
return groupedCalorieItems[date]!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let calorieCell = tableView.dequeueReusableCell(withIdentifier: "CalorieCell") as! CalorieCell
let date = dateSectionTitle[indexPath.section]
let caloriesToDisplay = groupedCalorieItems[date]![indexPath.row]
calorieCell.configure(withCalorieItems: caloriesToDisplay.foodList)
return calorieCell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let calorieHeader = tableView.dequeueReusableCell(withIdentifier: "CalorieHeader") as! CalorieHeader
let headerTitle = dateSectionTitle[section]
calorieHeader.dateLbl.text = "Date: \(headerTitle)"
return calorieHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let calorieFooter = tableView.dequeueReusableCell(withIdentifier: "CalorieFooter") as! CalorieFooter
//Cell Total Code
let date = dateSectionTitle[section]
let subtotal = groupedCalorieItems[dispensary]?.map { $0.getCalorieTotal() }.reduce(0, +) ?? 0
calorieFooter.calorieTotal.text = String(subtotal!)
return calorieFooter
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 150
}
}
extension CalorieViewController: DeleteRowInTableviewDelegate {
func deleteRow(inTableview rowToDelete: Int) {
let picked = dateSectionTitle[rowToDelete]
let selectedCell = groupedCalorieItems[dod]
delete(selectedCell)
// calorieItems.remove(at: rowToDelete) // tried using this and I get an error code upon segueing back to the CalorieVC
tableView.reloadData()
}
}
import UIKit
protocol DeleteRowInTableviewDelegate: NSObjectProtocol {
func deleteRow(inTableview rowToDelete: Int)
}
class DeleteViewController: UIViewController {
var modifyItems: CartItem!
var delegate: DeleteRowInTableviewDelegate?
#IBOutlet weak var deleteLbl: UILabel!
#IBOutlet weak var deleteBtn: UIButton!
#IBOutlet weak var cancelBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if isMovingFromParent {
delegate!.deleteRow(inTableview: 1)
}
deleteLbl.text = "Are you sure you want to delete this Food Item from your calorie List?"
}
#IBAction func decline(_ sender: Any) {
dismiss(animated: true)
delegate!.deleteRow(inTableview: 1)
print("Delete Item")
}
#IBAction func cancel(_ sender: Any) {
dismiss(animated: true)
print("Cancel Delete")
}
}
Remove the value from the dataSource
Remove the table cell
extension CalorieViewController: DeleteRowInTableviewDelegate {
func deleteRow(inTableview rowToDelete: Int) {
if caloriesItems.count > rowToDelete {
calorieItems.remove(at: rowToDelete)
tableView.deleteRows(at: [IndexPath(row: rowToDelete, section: 0)], with: .automatic)
} else {
print("index not present")
}
}
}
Do not call reloadData just to delete one row. This is a bad practice.
Use deleteRows instead.

Random Ads between cells

I am trying to put Ads totally randomly between cells inside a UITableView. I am gonna show my main file to you understand what I am doing and how I want:
Table View Controller:
class Page1: UITableViewController, UISearchBarDelegate {
#IBOutlet weak var searchBar: UISearchBar!
var employeesSearching = [Employee]()
var isSearching : Bool = false
#IBOutlet weak var GoogleBannerView: GADBannerView!
let collation = UILocalizedIndexedCollation.current()
var sections: [[Any]] = []
var objects: [Any] = [] {
didSet {
let selector: Selector = #selector(getter: UIApplicationShortcutItem.localizedTitle)
sections = Array(repeating: [], count: collation.sectionTitles.count)
let sortedObjects = collation.sortedArray(from: objects, collationStringSelector: selector)
for object in sortedObjects {
let sectionNumber = collation.section(for: object, collationStringSelector: selector)
sections[sectionNumber].append(object as AnyObject)
}
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.tableView.contentOffset = CGPoint(x: 0, y: searchBar.frame.height) //hide searchBar
Shared.instance.employees.sort {
(first, second) in
first.name.compare(second.name, options: .diacriticInsensitive) == .orderedAscending
}
}
func getMatches(letter: String, withArray array: [Employee]) -> [Employee] {
return array.filter({ ($0.name.compare(letter, options: .diacriticInsensitive, range: $0.name.startIndex..<$0.name.index($0.name.startIndex, offsetBy: 1), locale: nil) == .orderedSame)})
}
override func numberOfSections(in tableView: UITableView) -> Int {
if isSearching { return 1 }
return collation.sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let letter = collation.sectionTitles[section]
if isSearching {
return employeesSearching.count
} else {
let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
if !matches.isEmpty { return matches.count }
}
return 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if isSearching { return nil }
let letter = collation.sectionTitles[section]
let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
if matches.count == 0 { return nil }
return collation.sectionTitles[section] }
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if isSearching { return nil }
return collation.sectionIndexTitles }
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return collation.section(forSectionIndexTitle: index) }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 3 || indexPath.row == 9 || indexPath.row == 14 {
let cellAd = tableView.dequeueReusableCell(withIdentifier: "cellAd", for: indexPath)
GoogleBannerView?.adUnitID = "ca-app-pub-6043248661561548/4628935113"
GoogleBannerView?.rootViewController = self
GoogleBannerView?.load(GADRequest())
return cellAd
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
if isSearching {
cell.nameLabel.text = employeesSearching[indexPath.row].name
cell.positionLabel.text = employeesSearching[indexPath.row].position
} else {
let letter = collation.sectionTitles[indexPath.section]
let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
cell.nameLabel.text = matches[indexPath.row].name
cell.positionLabel.text = matches[indexPath.row].position
}
return cell
}
...
}
How do I smuggle a UITableViewCell as! AdCell randomly into the UITableView?
I mean, what should I do in cellForRowAt? I am a bit confused between all these indexed sections.
Firstly you need to generate a random number between 0 and your tableView Datasource array size
let lower : UInt32 = 0
let upper : UInt32 = array.count
let randomIndex = arc4random_uniform(upper - lower) + lower
then you need to add the Ad object in the array at the randomIndex
array.insert(AdObject, atIndex:randomIndex)
then just reload your tableView and handle the different types in cellForRow function
One approach would be to insert some sort of "ad" object at desired locations within your data model.
Then update cellForRowAt to look at the object in the data model for the given index path. If it's an "ad" object, create and setup an "ad" cell. Otherwise create and setup an appropriate data cell as you do now.

Swift - when is data actually loaded in TableViewController

I'm very much a Swift beginner - am populating a table view from Firebase data.
In the table footer I want to display some calculated totals under the table columns. However when calling footerCell.configure(priceLines, isPortrait: isPortrait) the priceLines dictionary is still empty.
How to remedy this?
Thanks in advance, André Hartman, Belgium
import UIKit
import FirebaseDatabase
class ListTableViewController: UITableViewController {
var priceLines = [NSDictionary]()
var isPortrait = false
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ListTableViewController.rotated), name: UIDeviceOrientationDidChangeNotification, object: nil)
loadDataFromFirebase()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return priceLines.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("profileCell", forIndexPath: indexPath) as! PriceTableViewCell
cell.configure(priceLines, row: indexPath.row, isPortrait: isPortrait, source: "intraday")
return cell
}
override func tableView(tableView: UITableView,viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell
headerCell.configure(isPortrait)
return headerCell
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerCell = tableView.dequeueReusableCellWithIdentifier("FooterCell") as! CustomFooterCell
footerCell.configure(priceLines, isPortrait: isPortrait)
return footerCell
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 30.0
}
override func tableView (tableView:UITableView, heightForHeaderInSection section:Int) -> CGFloat
{
return 50.0;
}
// MARK:- Load data from Firebase
func loadDataFromFirebase() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
refInter.observeEventType(.Value, withBlock: { snapshot in
var tempItems = [NSDictionary]()
for item in snapshot.children {
let child = item as! FIRDataSnapshot
let dict = child.value as! NSDictionary
tempItems.append(dict)
}
self.priceLines = tempItems
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
func rotated()
{
let newDisplay = (UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
if(newDisplay != isPortrait){
self.tableView.reloadData()
}
isPortrait = newDisplay
}
}
The documentation clearly says that
When the table view is about to appear the first time it’s loaded, the
table-view controller reloads the table view’s data.
So, it will reload the table automatically somewhere between viewDidLoad and viewWillAppear. Your priceLines is empty at this point and will be populated with data only when the closure in the method loadDataFromFirebase is fired. I'm not sure when it happens in your case, but as you call implicitly reloadData then you should have already priceLines nonempty (of course if the results in the closure have some data)