Terminating app due to uncaught exception 'RLMException', reason: 'Index 0 is out of bounds (must be less than 0).' Swift

Viewed 2180

I am trying to make a productivity app. The code is as follows:

import Foundation
import RealmSwift

class TimeCardData: Object {
    @objc dynamic var clockIn3: String = ""
    @objc dynamic var clockOut3: String = ""
    @objc dynamic var minutes3: Int = 0
    @objc dynamic var productivity3: String = ""
    @objc dynamic var lunch3: String = ""
    @objc dynamic var groupNumber3: String = ""
    @objc dynamic var group3: String = ""
    @objc dynamic var timeWorked3: String = ""
    @objc dynamic var clockInDate3 = ""
    @objc dynamic var hoursWorked3: String = ""
}

class TimeCardViewController: UIViewController {
    
    let realm = try! Realm()
    
    var timeCardData : Results<TimeCardData>?
    
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!
    
    var clockInDate2 = ""
    var hoursWorked2 = ""
    var timeWorked2 = ""
    var productivity2 = ""
    var clockIn2 = ""
    var clockOut2 = ""
    var lunch2 = ""
    var minutes2 = 0
    var groupNumber2 = ""
    var group2 = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 100.0
        loadTimeCardData()

    }
    
    func saveTimeCardData(timeCardData: TimeCardData) {
        do {
            try realm.write {
                realm.add(timeCardData)
            }
        } catch {
            print("Error saving TimeCard Data \(error)")
        }
        
        tableView.reloadData()
    }
    
    func loadTimeCardData() {
        
        timeCardData = realm.objects(TimeCardData.self)
        tableView.reloadData()
    }
}

extension TimeCardViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return timeCardData?.count ?? 1
            
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: "TimeCardCell", for: indexPath) as! TimeCardTableViewCell
        
        cell.productivity?.text = timeCardData?[indexPath.row].productivity3
        cell.hoursWorked?.text = timeCardData?[indexPath.row].hoursWorked3
        cell.clockInDate?.text = timeCardData?[indexPath.row].clockInDate3
        cell.timeWorked?.text = timeCardData?[indexPath.row].timeWorked3
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let TCD = TimeCardData()
            TCD.clockIn3 = clockIn2
            TCD.clockOut3 = clockOut2
            TCD.group3 = group2
            TCD.lunch3 = lunch2
            TCD.minutes3 = minutes2
            TCD.groupNumber3 = groupNumber2
            TCD.productivity3 = productivity2
            TCD.timeWorked3 = timeWorked2
            TCD.clockInDate3 = clockInDate2
            TCD.hoursWorked3 = hoursWorked2
            
            saveTimeCardData(timeCardData: TCD)
        
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            
            do {
                       try realm.write {
                        let cellToBeDeleted = timeCardData![indexPath.row]
                        realm.delete(cellToBeDeleted)
                       }
                   } catch {
                       print("Error deleting TimeCard Data \(error)")
                   }
        }
    }
}

The problem is on numberOfRowsInSection, when I return timeCardData?.count ?? 1, it is not bringing any cells on my table. I presume it returns 0 and therefore it does not bring a cell. If I just return 1 or any other number or anything other than the above, the app crashes and gives me the 'Index 0 is out of bounds (must be less than 0).' reason for crashing. This is one of my first apps and I am stuck and do not know how to get around this. What am I doing wrong and how can I proceed from this point onwards?

2 Answers

I was getting the same RLMException . I found out my mistake is that i'm fetching the objects from Realm like:

let objects = realm.objects(PlaylistItem.self)

and sending exact same objects to the delete function of realm:

realm.delete(objects)

which are of type Results and get updated on each delete(are reference types)..

so the answer for me was to pass in a copy of items you wanna delete by using Array()

realm.delete(Array(objects))

Well for me the problem actually lied in a separate place. Because I was using an external resource to add a slide-to-delete functionality in my app, it turned out that the intrinsic code which I was using to call that functionality was flawed. Instead of referring to a tableView, I ended up referring to collectionView

That was the reason why the application crashed.

Related