核心数据:如何检查数据是否在连续日期?

时间:2016-09-05 16:40:18

标签: ios swift core-data

我在用户完成“锻炼”后保存核心数据,并希望能够检查用户已经计算出的日期是否是连续的顺序。我已经使用下面的代码来检查用户是否在点击日历的那一天计算出来了,但是无法考虑如何检查日期是否连续。

起初我想考虑保存的NSDate的.Day并查看日期是否有序,但是这个月在月份变化的情况下连续几天不起作用,例如从31日到1月1日。

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext

OuterLoop:  do {
    let request = NSFetchRequest(entityName: "Workout")
    let workoutResults = try context.executeFetchRequest(request) as! [Workout]

    if workoutResults.count > 0 {
        for item in workoutResults {
            let workoutDateDay = NSCalendar.currentCalendar().component(.Day, fromDate: item.workoutDate!)

            if workoutDateDay == dayView.date.day {

                let convertedTime:Int = Int(item.workoutTime!)
                let convertedNumberOfWorkouts: Int = Int(item.workoutNumber!)
                tempArray.append(convertedTime)
                tempArrayWorkoutNumber.append(convertedNumberOfWorkouts)

1 个答案:

答案 0 :(得分:0)

func consecutiveDatesCheck(dateArray: [NSDate]) -> Int {

    // The incoming parameter dateArray is immutable, so first make it mutable
    var mutableArray = dateArray

    // Next, sort the incoming array
    mutableArray.sortInPlace({ $0.compare($1) == NSComparisonResult.OrderedAscending })

    var x = 0
    var numberOfConsecutiveDays = 1
    var streakArray = [Int]()

    // Cycle through the array, comparing the x and x + 1 elements
    while x + 1 < mutableArray.count {

        let calendar: NSCalendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Day, fromDate: mutableArray[x], toDate: mutableArray[x + 1], options: [])

        // If the difference between the dates is greater than 1, append the streak to streakArray and reset the counter
        if abs(components.day) > 1 {
            streakArray.append(numberOfConsecutiveDays)
            numberOfConsecutiveDays = 1
        }

        // If the difference between the days is exactly 1, add one to the current streak
        else if abs(components.day) == 1 {
            numberOfConsecutiveDays += 1
        }

        x += 1
    }

    // Append the final streak to streakArray
    streakArray.append(numberOfConsecutiveDays)
    print(streakArray)

    // Return the user's longest streak
    return streakArray.maxElement()!
}

然后在调用函数时:

   do {
        let request = NSFetchRequest(entityName: "Workout")
        let workoutResults = try context.executeFetchRequest(request) as! [Workout]

        if workoutResults.count > 0 {

            // Declare a new empty array
            var dateArray = []

            for item in workoutResults {
                dateArray.append(item.workoutDate!)
            }

            consecutiveDatesCheck(dateArray)
        }
    } catch {
        print("Error loading data")
    }