领域项目添加到表视图后出现两次

时间:2019-02-09 10:32:00

标签: swift uitableview realm cocoapods

我正在开发一个应用程序,您可以在其中使用Realm数据库将项目添加到表视图中。目前,我可以将一个项目添加到“表视图”中,但是它已两次添加到“领域数据库”中。这意味着,如果我关闭我的应用程序然后再回到它,则我之前添加的新项目出现两次,一次位于新位置,一次替换其上方表格视图中的项目。附件是我的代码。我尝试了各种不同的方法,但无法弄清楚该如何解决。谢谢您的帮助!

这是我将项目添加到Table View / 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)

}
}

1 个答案:

答案 0 :(得分:0)

我设法通过使用类型为RealmEventItem()的新变量解决了该问题 现在,已更改的代码(在try!realm.write中)如下:

 try! realm.write {

           //The concept of adding a newEventItem of type RealmEventItem() & and then adding all the values to it rather than direct to the RealmEventItem() fixed the problem of the new items replacing the previous ones.
            let newEventItem = RealmEventItem()

            // Joining the Day & Month Together
            let fullDateOfEvent = self.dayOfEvent.text! + " " + self.monthOfEvent.text!
            // Making Variables to give a boolean of whether the user would like reminders
            var oneDayReminderItem = false
            var sevenDayReminderItem = false

            if self.oneDayReminder.text == "Yes" {
                oneDayReminderItem = true
            } else {oneDayReminderItem = false}

            if self.sevenDayReminder.text == "Yes" {
                sevenDayReminderItem = true
            } else {sevenDayReminderItem = false}

            //Setting the values to the newEventItem --> which is part of the RealmEventItem()
            newEventItem.nameOfEventRealm = self.nameOfEvent.text!
            newEventItem.dateOfEventRealm = fullDateOfEvent
            newEventItem.oneDayBeforeReminderRealm = oneDayReminderItem
            newEventItem.sevenDaysBeforeReminderRealm = sevenDayReminderItem


            // 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.add(newEventItem, update: false)
                realm.create(RealmEventItem.self, value: newEventItem, update: false)
                self.tableView.insertRows(at: [IndexPath.init(row: realmEventList.count-1, section: 0)], with: .automatic)

                //By Adding the following 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!")
            }
            }

希望这对以后的人有帮助!