简体   繁体   中英

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. My model (SIMCourse) has two attributes - startDate and endDate that are NSDate objects. 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. 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.

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. Can anyone help point me in the right direction?

(newStartDate, newEndDate) overlaps with (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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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