简体   繁体   English

核心数据 - 查找具有重叠日期范围的记录

[英]Core Data - Finding records with overlapping date ranges

I'm working on an iOS application with Core Data that tracks scheduling of training courses and associated data. 我正在开发一个带有Core Data的iOS应用程序,用于跟踪培训课程和相关数据的安排。 My model (SIMCourse) has two attributes - startDate and endDate that are NSDate objects. 我的模型(SIMCourse)有两个属性 - startDateendDate是NSDate对象。 So far, so good. 到现在为止还挺好。

I'm now working on adding a feature to prevent scheduling two courses during the same time. 我现在正在努力添加一项功能,以防止在同一时间安排两个课程。 So, when I create a new SIMCourse, I'd like to check whether its date range overlaps with any other existing SIMCourse's date range. 因此,当我创建新的SIMCourse时,我想检查其日期范围是否与任何其他现有SIMCourse的日期范围重叠。 In other words, if my new course runs January 1-3, and I have an existing course that runs January 2-4, that's obviously a conflict. 换句话说,如果我的新课程在1月1日至3日运行,并且我有一个运行在1月2日至4日的课程,那显然是一个冲突。

I know I could fetch all the SIMCourse objects in my data store and iterate through them, but I'm not at all confident this is the best way. 我知道我可以获取数据存储中的所有SIMCourse对象并遍历它们,但我完全不相信这是最好的方法。 Can anyone help point me in the right direction? 谁能帮助我指出正确的方向?

(newStartDate, newEndDate) overlaps with (startDate, endDate) if (newStartDate, newEndDate)重叠(startDate, endDate) if

(newStartDate <= endDate) && (startDate <= newEndDate)

(That is almost what @Bergasms suggested, but not exactly. If I am mistaken here, credits should go to him.) (这几乎是@Bergasms建议的,但不完全是。如果我在这里弄错了,应该归功于他。)

You can use the following fetch request to check for overlapping courses: 您可以使用以下获取请求来检查重叠课程:

NSDate *newStartDate = ...;
NSDate *newEndDate = ...;

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SIMCourse"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ <= endDate) AND (startDate <= %@)",
                                      newStartDate, newEndDate];
request.predicate = predicate;
NSArray *results = [context executeFetchRequest:request error:&error];
if (error == nil) {
    // handle error
} else if (results.count == 0) {
    // no overlapping entries
} else {
    //overlapping entries in results array
}

I have assumed here that two courses overlap if the end date of one course is equal to the start date of the other course. 如果一门课程的结束日期等于另一门课程的开始日期,我假设这里有两门课程重叠。 If such intervals are not considered as "overlapping", you can just replace <= by < in the predicate. 如果这些间隔不被视为“重叠”,则可以在谓词中替换<= by <

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM