4

这是我的代码:

NSString * calID = [[NSUserDefaults standardUserDefaults] objectForKey:@"calendarIdentifier"];
EKCalendar *cal = [eventStore calendarWithIdentifier:calID];

// If calendar exists
if(cal)
{
    // Retrieve all existing events until today
    NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:[NSDate distantPast] endDate:[NSDate date] calendars:@[cal]];
    self.events = [eventStore eventsMatchingPredicate:predicate];

    if(self.events==nil)
        NSLog(@"nil events!");
 }

calendarItentifier 是我在程序中创建日历时存储的变量,因此我不会在错误的日历上添加事件。

但是,该代码无法检索日历上的过去事件,它只是将 nil 返回给 self.events。但我确实在日历上添加了事件。有什么可以告诉我代码是否有问题?

4

3 回答 3

10

根据this answerthis postEKEventStore eventsMatchingPredicate:不支持相隔超过四年startDate的谓词。endDate我找不到关于这个事实的任何官方文档,但在实践中,该方法似乎只在endDate4 年后返回事件startDate,以先到者为准。

[NSDate distantPast]返回过去几个世纪的日期,因此如果您创建一个以此作为开始日期的谓词,您几乎肯定会得到错误的答案。

最简单的解决方案是将您的代码更改为以下内容:

NSDate* fourYearsAgo = [NSDate dateWithTimeIntervalSinceNow:-1 * 60 * 60 * 24 * 365 * 4];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fourYearsAgo endDate:[NSDate date] calendars:@[cal]];

如果这对您不起作用,您要么必须找到一种更明智地选择界限的方法,要么创建连续的四年谓词,直到找到所需的内容。

于 2013-11-18T18:45:31.120 回答
0

最可能的原因eventStorenil。任何时候你遇到“似乎什么都没有发生”的错误,你应该首先查看是否有nil.

于 2013-11-06T21:49:13.410 回答
0

对我来说,这是因为 startDate 和 endDate 相同。为了解决这个问题,我将查询中的 endDate 增加了一秒,它现在返回事件。

于 2017-02-09T23:14:57.393 回答