删除和重新创建 EKCalendar

Deleting and recreating EKCalendar

在我的应用程序中,我在 EKCalendar 中创建事件。我在线获取事件,为了刷新事件,我想先删除日历(如​​果存在),重新创建它,然后将新事件放在那里。

实例化我使用的日历

- (EKCalendar *)calendar {
    if (!_calendar) {
        NSArray *calendars = [self.store calendarsForEntityType:EKEntityTypeEvent];
        NSString *calendarTitle = @"MyCalendar";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title matches %@", calendarTitle];
        NSArray *filtered = [calendars filteredArrayUsingPredicate:predicate];

        if ([filtered count]) {
            _calendar = [filtered firstObject];
        } else {
            _calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.store];
            _calendar.title = calendarTitle;
            _calendar.source = self.store.defaultCalendarForNewEvents.source;
            NSError *calendarErr = nil;
            BOOL calendarSuccess = [self.store saveCalendar:_calendar commit:YES error:&calendarErr];
            if (!calendarSuccess) {
                NSLog(@"Calendar Error = %@", [calendarErr localizedDescription]);
            }
        }
    }
    return _calendar;
}

要删除日历,我使用

-(IBAction)deleteCalendar{
    NSError *error = nil;
    [self.store removeCalendar:_calendar commit:YES error:&error];

}

这两种方法单独使用都很好。 因此,当我开始创建事件时,我会执行以下操作:

[self deleteCalendar];//delete calendar and its events, in case it already exists
[self calendar];//create calendar
[self importEvents];//put events in calendar

现在,我观察到的是:

在应用程序的第一个运行

当应用程序处于 运行ning 状态时,我用一个按钮再次触发了上述方法。结果如下,令我费解:

请指教

更新:

这可能是正在发生的事情的一个指标,但我还是不明白:

一段时间后,事件出现在不同的日历中,即不是名为'myCalendar'的日历,而是另一个基于 iCloud 的日历,显然是在那一点是 defaultCalendarForNewEvents。但是,这对我来说也没有任何意义。

好的,所以,发生了什么: 我已经从商店中有效地删除了日历,但对该日历的引用实际上仍然存在于我的应用程序中。 我是这样解决的:

-(IBAction)deleteCalendar:(id)sender{
    NSError *error = nil;
    if(_calendar){
        [self.store removeCalendar:_calendar commit:YES error:&error];
    }
    _calendar = nil;
}

我希望这对某人有用