如何使用上一个CoreData条目验证今天的日期

时间:2015-12-17 10:30:16

标签: ios swift core-data

我有一个 CoreData 属性2(值,日期)。当我点击 UIButton 时,它会添加一个与 UIButton 的值对应的条目。

我希望限制每日加入。基本上,我希望检查当前日期和最后一个条目的日期。如果它的值相同,则不会添加

我的功能

func data(sender: UIButton) {

    // Date Format

    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "YYYY/MM/dd"
    let dateFormat = formatter.stringFromDate(date)


    // Load Entity

    let AppDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let theContext : NSManagedObjectContext = AppDel.managedObjectContext
    let theEnt = NSEntityDescription.entityForName("Mood", inManagedObjectContext: theContext)


    // Create Item

    let newItem = Mood(entity: theEnt!, insertIntoManagedObjectContext: theContext)
    newItem.mood = String(sender.tag)
    newItem.date = dateFormat

    // Save Item

    do {

        try theContext.save()

    } catch _ {

    }

}

提前感谢您的回复。

2 个答案:

答案 0 :(得分:2)

我为此使用NSDate扩展名。

extension NSDate {
    class func areDatesSameDay(dateOne:NSDate,dateTwo:NSDate) -> Bool {
        let calender = NSCalendar.currentCalendar()
        let flags: NSCalendarUnit = [.Day, .Month, .Year]
        let compOne: NSDateComponents = calender.components(flags, fromDate: dateOne)
        let compTwo: NSDateComponents = calender.components(flags, fromDate: dateTwo);
        return (compOne.day == compTwo.day && compOne.month == compTwo.month && compOne.year == compTwo.year);
    }
}

用法就是这样。

if NSDate.areDatesSameDay(dateOne, dateTwo: dateTwo) {
    // Dates are same day
} else {
    // Dates are not the same day
}

@Tom Harrington 刚刚指出您可以使用NSCalendar方法更简单地执行此操作

let calender = NSCalendar.currentCalendar()
if calender.isDate(dateOne, inSameDayAsDate: dateTwo) {
    // Dates are same day
}

所以我们可以让我的可爱扩展更简单...

extension NSDate {
    func isSameDayAs(date:NSDate) -> Bool {
        let calender = NSCalendar.currentCalendar()
        return calender.isDate(self, inSameDayAsDate: date)
    }
}

然后像这样使用它。

if dateOne.isSameDayAs(dateTwo) {
    // Dates are same day
} else {
    // Dates are not the same day
}

那就是 Numberwang!

答案 1 :(得分:2)

如果您获取Mood个对象,按date降序排序,则返回的第一个项目将是最后一个条目。您可以将fetchLimit设置为1,以避免加载超出必要的对象。然后,您可以测试以查看date属性是否匹配,并相应地处理:

func data(sender: UIButton) {
    // Date Format
    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "YYYY/MM/dd"
    let dateFormat = formatter.stringFromDate(date)    
    // Get context and entity details    
    let AppDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let theContext : NSManagedObjectContext = AppDel.managedObjectContext
    let theEnt = NSEntityDescription.entityForName("Mood", inManagedObjectContext: theContext)
    // Fetch the latest entry
    let fetch = NSFetchRequest()
    fetch.entity = theEnt!
    let sort = NSSortDescriptor(key: "date", ascending:false)
    fetch.sortDescriptors = [sort]
    fetch.fetchLimit = 1
    let results = try! theContext.executeFetchRequest(fetch) as! [Mood]
    // NB should do proper try/catch error checking
    // Check for existing entry
    if (results.count > 0) {
        // Check whether date matches
        if (results[0].date != dateFormat) {
            let newItem = Mood(entity: theEnt!, insertIntoManagedObjectContext: theContext)
            newItem.mood = String(sender.tag)
            newItem.date = dateFormat
        }
    } else { // No entries yet, I assume you want to add one...
        let newItem = Mood(entity: theEnt!, insertIntoManagedObjectContext: theContext)
        newItem.mood = String(sender.tag)
        newItem.date = dateFormat
    }
    // Save Item    
    do {
        try theContext.save()
    } catch _ {    
    }
}

请注意(给定您的代码newItem.date = dateFormat)我假设date属性是您使用相同格式设置的字符串(" YYYY / MM / dd")。这剥夺了时间信息,因此避免了日期比较的需要,但也有一个优点,即字符串排序等同于日期排序(可能因此您选择了该格式)。如果date实际上是Date属性,则排序仍然有效,但您需要使用日期比较。