为什么eventsMatchingPredicate返回nil?

时间:2013-11-06 21:45:09

标签: ios cocoa-touch ekevent

这是我的代码:

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。但我DID在日历上添加事件。可以告诉我代码是否有任何问题吗?

3 个答案:

答案 0 :(得分:9)

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

[NSDate distantPast]会返回a date centuries in the past,因此如果您创建一个谓词作为开始日期,那么您几乎可以得到错误的答案。

最简单的解决方案是将代码更改为:

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

如果这不适合你,你要么必须找到更明智地选择界限的方法,要么创建连续的四年谓词,直到找到你想要的为止。

答案 1 :(得分:0)

最可能的原因是eventStorenil。每当你遇到“似乎没有发生”的错误时,你应该首先查看是否有nil

答案 2 :(得分:0)

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