Swift代码将不需要的零数据添加到核心数据中

时间:2016-10-28 00:44:16

标签: ios swift core-data

我正在尝试添加提醒,并将用户日历添加到我的应用中。但是我遇到了一个问题,当我尝试加载保存在核心数据中的数据时,我得到的是零。加载几次后,我只获得nil数据,但每次重新加载应用程序时都会增加。

addReminderToCalendar函数

/*
 *
 *This function adds the reminder to the devices calendar and to the devices local storage
 *
 */
func addReminderToCalendar(newReminder : Reminder){
    print("adding reminder :" + newReminder.reminderName)
    /*print(newReminder.reminderDescription)
     print(newReminder.reminderDate)
     print(newReminder.reminderID)
     print(newReminder.reminderName)*/
    if(newReminder.reminderID != nil && newReminder.reminderDate != nil && newReminder.reminderDescription != nil && newReminder.reminderName != nil){
        //print("Adding Reminder to Calendar")
        let appDelegate = UIApplication.shared.delegate as! AppDelegate!
        let managedContext = appDelegate?.managedObjectContext
        let entity =  NSEntityDescription.entity(forEntityName: "Reminders", in:managedContext!)
        let reminderDB = NSManagedObject(entity: entity!, insertInto: managedContext)
        //  print("Reminder ID :" + String(newReminder.reminderID))
        if(checkForReminder(newReminder) == -1){//Checking that the reminder is not already added
            print("addReminderToCalendar :")
            print(newReminder.reminderID)
            reminderDB.setValue(newReminder.reminderID, forKey: "reminderID")
            reminderDB.setValue(newReminder.reminderName, forKey: "reminderName")
            reminderDB.setValue(newReminder.reminderDescription, forKey: "reminderDescription")
            reminderDB.setValue(newReminder.reminderDate, forKey: "reminderDate")
            reminders.append(newReminder)
        }
        if (managedContext?.hasChanges)! {
            do {
                try managedContext?.save()
            } catch {
                //print(newReminder)
                NSLog("Error Here")
            }
        }
    }else{
        print("The reminder to be added was nil")
    }
}

loadReminder函数

    /*
 * This function loads the reminders that have been stored in the device
 */
func loadReminders(){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Reminders")

    let results = try? managedContext.fetch(fetchRequest)

    storedReminders = results as! [NSManagedObject]
    print(storedReminders.count)
    //print(storedReminders[0].value(forKey: "reminderID"))
    if (storedReminders.count > 0){
        for index in 0 ... storedReminders.count - 1{
            print("Loading reminder with ID : ")
            print(storedReminders[index].value(forKey: "reminderID"))
            print("Loading reminder with Name : ")
            print(storedReminders[index].value(forKey: "reminderName"))

            if(storedReminders[index].value(forKey: "reminderID") != nil && storedReminders[index].value(forKey: "reminderName") != nil && storedReminders[index].value(forKey: "reminderDescription") != nil && storedReminders[index].value(forKey: "reminderDate") != nil){ //checking that the values are not null
                let loadedReminder = Reminder()
                loadedReminder.reminderID = storedReminders[index].value(forKey: "reminderID") as! Double
                loadedReminder.reminderName = storedReminders[index].value(forKey: "reminderName") as! String
                loadedReminder.reminderDescription = storedReminders[index].value(forKey: "reminderDescription") as! String
                loadedReminder.reminderDate = (storedReminders[index].value(forKey: "reminderDate") as! NSDate) as Date!
                reminders.append(loadedReminder)
            }
        }
    }
}

提醒课程

import Foundation
import UIKit
import CoreData

class Reminder :UICollectionViewCell{

   var reminderDate: Date!
   var reminderDescription: String!
   var reminderID: Double!
   var reminderName: String!

}

修改 我已经在我的加载提醒中添加了以下行,这是为了阻止核心数据填充nil值。                 }其他{                     //删除此提醒                     managedContext.delete(storedReminders [index] as NSManagedObject)                     打印(&#34;删除数据&#34;)                 } 所以我的loadReminders函数现在看起来像这个

/ *  *此功能加载已存储在设备中的提醒  * / func loadReminders(){

let appDelegate = UIApplication.shared.delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext

let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Reminders")

let results = try? managedContext.fetch(fetchRequest)

storedReminders = results as! [NSManagedObject]
print(storedReminders.count)
//print(storedReminders[0].value(forKey: "reminderID"))
if (storedReminders.count > 0){
    for index in 0 ... storedReminders.count - 1{
        print("Loading reminder with ID : ")
        print(storedReminders[index].value(forKey: "reminderID"))
        print("Loading reminder with Name : ")
        print(storedReminders[index].value(forKey: "reminderName"))

        if(storedReminders[index].value(forKey: "reminderID") != nil && storedReminders[index].value(forKey: "reminderName") != nil && storedReminders[index].value(forKey: "reminderDescription") != nil && storedReminders[index].value(forKey: "reminderDate") != nil){ //checking that the values are not null
            let loadedReminder = Reminder()
            loadedReminder.reminderID = storedReminders[index].value(forKey: "reminderID") as! Double
            loadedReminder.reminderName = storedReminders[index].value(forKey: "reminderName") as! String
            loadedReminder.reminderDescription = storedReminders[index].value(forKey: "reminderDescription") as! String
            loadedReminder.reminderDate = (storedReminders[index].value(forKey: "reminderDate") as! NSDate) as Date!
            reminders.append(loadedReminder)
        }else{
                //delete this reminder
                managedContext.delete(storedReminders[index] as NSManagedObject)
                print("deleted data")
            }
    }
}

}

1 个答案:

答案 0 :(得分:1)

在这里,您要创建一个新的Reminders实例并将其添加到NSManagedObjectContext

let entity =  NSEntityDescription.entity(forEntityName: "Reminders", in:managedContext!)
let reminderDB = NSManagedObject(entity: entity!, insertInto: managedContext)

然后检查是否已添加:

if(checkForReminder(newReminder) == -1)

这是我认为问题所在。您已将Reminders实例添加到您的上下文中!因此managedContext?.hasChanges将是true

上下文发生了变化,这些Reminders将与所有实体属性及其默认值一起保存。我假设它们默认为nil

这应该解决它,虽然你的代码部分我看不出来,所以把它带上了一粒盐......

func addReminderToCalendar(newReminder: Reminder) {
    if(newReminder.reminderID != nil && newReminder.reminderDate != nil && newReminder.reminderDescription != nil && newReminder.reminderName != nil) {
        if(checkForReminder(newReminder) == -1) {
            let appDelegate = UIApplication.shared.delegate as! AppDelegate!
            let managedContext = appDelegate?.managedObjectContext
            let entity =  NSEntityDescription.entity(forEntityName: "Reminders", in:managedContext!)
            let reminderDB = NSManagedObject(entity: entity!, insertInto: managedContext)
            reminderDB.setValue(newReminder.reminderID, forKey: "reminderID")
            reminderDB.setValue(newReminder.reminderName, forKey: "reminderName")
            reminderDB.setValue(newReminder.reminderDescription, forKey: "reminderDescription")
            reminderDB.setValue(newReminder.reminderDate, forKey: "reminderDate")
            reminders.append(newReminder)

            if (managedContext?.hasChanges)! {
                do {
                    try managedContext?.save()
                } catch {
                    NSLog("Error Here")
                }
            }
        }
    } else {
        print("The reminder to be added was nil")
    }
}