Я занимаюсь разработкой приложения, в котором вы можете добавлять элементы в табличное представление с помощью базы данных Realm.На данный момент я могу добавить элемент в представление таблицы, но он добавляется дважды в базу данных области.Это означает, что если я закрою свое приложение и вернусь в него, новый элемент, который я ранее добавил, появится дважды, один раз в новой позиции и один раз заменив элемент, который был в табличном представлении чуть выше него.Прикреплен мой код.Я пробовал разные вещи, но просто не могу понять, как это исправить.Спасибо за вашу помощь!
Это код, в который я добавляю элемент в свою таблицу / базу данных области:
extension MainTableViewController {
func createNewEventAlertView () {
let newEventAlert = PMAlertController(title: "New Event Alert", description: "", image: nil, style: .alert)
newEventAlert.addTextField { (eventNameAlertTextField) in
eventNameAlertTextField?.placeholder = "Event Name"
eventNameAlertTextField?.adjustsFontSizeToFitWidth = true
eventNameAlertTextField?.textAlignment = .center
eventNameAlertTextField?.text! = nameOfEvent.text!
nameOfEvent = eventNameAlertTextField!
}
newEventAlert.addTextField { (dayEventDateTextField) in
dayEventDateTextField?.placeholder = "Day Of The Month"
dayEventDateTextField?.inputView = dayPickerView
dayOfEvent = dayEventDateTextField!
}
newEventAlert.addTextField { (monthEventDateTextField) in
monthEventDateTextField?.placeholder = "Month"
monthEventDateTextField?.inputView = monthPickerView
monthOfEvent = monthEventDateTextField!
}
newEventAlert.addTextField { (remindOneDayBeforeTextField) in
remindOneDayBeforeTextField?.placeholder = "Remind 1 Day Before?"
remindOneDayBeforeTextField?.inputView = oneDayPickerView
oneDayReminder = remindOneDayBeforeTextField!
}
newEventAlert.addTextField { (remindSevenDaysBeforeTextField) in
remindSevenDaysBeforeTextField?.placeholder = "Remind 7 Days Before?"
remindSevenDaysBeforeTextField?.inputView = sevenDayPickerView
sevenDayReminder = remindSevenDaysBeforeTextField!
}
newEventAlert.addAction(PMAlertAction(title: "Add", style: .default, action: {
print("Add Event Button Pressed in Alert")
//Adding realmEventItem & its variables to the Database
try! realm.write {
//Adding the name & date of the Event to the Realm Database Item
self.realmEventItem.nameOfEventRealm = self.nameOfEvent.text!
let fullDateOfEvent = self.dayOfEvent.text! + " " + self.monthOfEvent.text!
self.realmEventItem.dateOfEventRealm = fullDateOfEvent
//Telling the Realm Database whether they wan't to be reminded one & seven days before the event
if self.oneDayReminder.text == "Yes" {
self.realmEventItem.oneDayBeforeReminderRealm = true
} else {self.realmEventItem.oneDayBeforeReminderRealm = false}
if self.sevenDayReminder.text == "Yes" {
self.realmEventItem.sevenDaysBeforeReminderRealm = true
} else {self.realmEventItem.sevenDaysBeforeReminderRealm = false}
// Making Sure there is something written in the Name & Date Text Fields before allowing anything to be added
if self.nameOfEvent.text != "" && self.dayOfEvent.text != "" && self.monthOfEvent.text != "" {
/*
- use create method instead of add method to add new entries,
- Because add method replaces last new entry with our previous entry,
- so every time only one object store in database
*/
realm.create(RealmEventItem.self, value: self.realmEventItem, update: false)
self.tableView.insertRows(at: [IndexPath.init(row: realmEventList.count-1, section: 0)], with: .automatic)
//By Adding the follwing line it has meant that my code no longer crashes when I add an Item, then delete it & then try and add another item again.
self.tableView.numberOfRows(inSection: realmEventList.count)
print(realmEventList.count)
self.labelWhenTableViewIsEmpty.text = ""
print("Add to Table View Called")
} else {
// Missing Boxes
print("Missing Information!")
}
// This makes sure that each time the user goes to add a new Event all the picker are reset
if self.nameOfEvent.text != "" { self.nameOfEvent.text = "" }
if self.dayPickerView.selectedRow(inComponent: 0) != 0 { self.dayPickerView.selectRow(0, inComponent: 0, animated: false) }
if self.monthPickerView.selectedRow(inComponent: 0) != 0 {self.monthPickerView.selectRow(0, inComponent: 0, animated: false)}
if self.oneDayPickerView.selectedRow(inComponent: 0) != 0 {self.oneDayPickerView.selectRow(0, inComponent: 0, animated: false)}
if self.sevenDayPickerView.selectedRow(inComponent: 0) != 0 {self.sevenDayPickerView.selectRow(0, inComponent: 0, animated: false)}
}
print("REAL DATA:::-- \(realm.objects(RealmEventItem.self))")
}))
newEventAlert.addAction(PMAlertAction(title: "Cancel", style: .cancel, action: {
print("Cancel Button Pressed in Alert")
}))
present(newEventAlert, animated: true, completion: nil)
}
}