Checking for duplicated items before adding new event in iOS - EKEventStore

≡放荡痞女 提交于 2019-12-05 07:11:04

Summary

At some point in your instance method (probably during the for loop) you will want to create an NSPredicate based on [allHolidayDates objectAtIndex:i] to return an array that you loop through to check if [allHolidayNames objectAtIndex:i] is present in the returned events.

Example code

for (int i = 0; i<[allHolidayNames count]; ++i) {

    // ------ EVENT MANIPULATION ------

    EKEventStore *eventStore = [[EKEventStore alloc] init];

    NSPredicate *predicateForEventsOnHolidayDate = [eventStore predicateForEventsWithStartDate:[allHolidayDates objectAtIndex:i] endDate:[allHolidayDates objectAtIndex:i] calendars:nil]; // nil will search through all calendars

    NSArray *eventsOnHolidayDate = [eventStore eventsMatchingPredicate:predicateForEventsOnHolidayDate]

    BOOL eventExists = NO;

    for (EKEvent *eventToCheck in eventsOnHolidayDate) {
        if ([eventToCheck.title isEqualToString:[allHolidayNames objectAtIndex:i]]) {
            eventExists = YES;
        }
    }

    if (eventExists == NO) {
        EKEvent *addEvent = [EKEvent eventWithEventStore:eventStore];
        addEvent.title = [allHolidayNames objectAtIndex:i];
        addEvent.startDate = [allHolidayDates objectAtIndex:i];
        addEvent.allDay = YES;
        [addEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
        [eventStore saveEvent:addEvent span:EKSpanThisEvent commit:YES error:nil];
    }
}

Tips

  • To help visualise the data, especially the contents of arrays and objects, try using NSLog. This will output the contents of an object to the console to help you understand the data structures a bit better.

    NSLog("eventsOnHolidayDate = %@",eventsOnHolidayDate);

  • Note that eventsMatchingPredicate will block the main thread whilst retrieving events. If your doing this multiple times in a row it could impact on the user experience. You should consider using enumerateEventsMatchingPredicate:usingBlock: (outside the scope of this question).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!