簡體   English   中英

如何使用最后一個CoreData條目驗證今天的日期

[英]How to verify today date with last CoreData entry

我有一個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 _ {

    }

}

預先感謝您的回復。

我為此使用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!

如果獲取Mood對象(按date降序排列),則返回的第一項將是最后一項。 您可以將fetchLimit設置為1,以避免加載fetchLimit對象。 然后,您可以測試日期屬性是否匹配,並進行相應處理:

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屬性,則排序仍然有效,但是您需要使用日期比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM