我正在尝试制作一个生产力应用程序。 代码如下:
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)")
}
}
}
}
问题出在
numberOfRowsInSection
上,当我返回timeCardData?.count ?? 1
时,在我的表格上没有带来任何单元格。我猜它返回了0,因此它没有带来单元格。如果我仅返回1或任何其他数字或任何其他内容,应用程序会崩溃并给我“索引0超出范围(必须小于0)”的原因。这是我第一个应用程序之一,我陷入困境,不知道如何解决这个问题。我做错了什么,我应该如何从这个点继续进行?