gpt4 book ai didi

ios - 核心数据: How to check if data is in consecutive dates?

转载 作者:行者123 更新时间:2023-11-30 13:06:11 25 4
gpt4 key购买 nike

我在用户完成“锻炼”后保存核心数据,并希望能够检查用户锻炼的日期是否按连续顺序排列。我使用下面的代码来检查用户是否在日历上单击的一天进行了锻炼,但无法想象如何检查这些天是否连续。

起初我想获取保存的 NSDate 的 .Day 并查看日期是否按顺序排列,但是当月份发生变化时,这对于连续几天不起作用,例如每月 31 日至 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)

最佳答案

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")
}

关于ios - 核心数据: How to check if data is in consecutive dates?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39334697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com