why eventsMatchingPredicate returns nil?

江枫思渺然 提交于 2020-01-14 10:38:52

问题


Here's my code:

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!");
 }

The calendarItentifier is the variable that I stored when I created the calendar in my program, so it's not the case I'm adding events on the wrong calendar.

However, the code does not work to retrieve past events on the calendar, it simply returns nil to self.events. But I DID add events on the calendar. Can anything tell me if there's anything wrong with the code?


回答1:


According to this answer and this post, EKEventStore eventsMatchingPredicate: doesn't support predicates with a startDate and endDate more than four years apart. I can't find any official documentation on this fact, but in practice the method appears to just return events up to endDate or four years after startDate, whichever comes first.

[NSDate distantPast] returns a date centuries in the past, so you're all but guaranteed to get a wrong answer if you create a predicate with that as your start date.

The simplest solution would be to change your code to something like this:

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

If this doesn't work for you, you'll either have to find a way to choose your bounds more wisely or create successive four-year predicates until you find what you're looking for.




回答2:


The most likely cause is that eventStore is nil. Any time you encounter a "nothing seems to happen" bug, you should first look to see if anything is nil.




回答3:


For me this occurred because the startDate and endDate were the same. To remedy this, I increased the endDate in the query by one second and it now returns the event.



来源:https://stackoverflow.com/questions/19823486/why-eventsmatchingpredicate-returns-nil

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