为什么eventsMatchingPredicate返回nil? [英] why eventsMatchingPredicate returns nil?

查看:477
本文介绍了为什么eventsMatchingPredicate返回nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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是我在我的程序中创建日历时存储的变量,所以不是这样,我在错误的日历上添加事件。

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.

然而,代码不能检索日历上的过去事件,它只是返回nil到self.events。但我DID添加日历上的事件。

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?

推荐答案

根据此答案此帖 EKEventStore eventsMatchingPredicate:不支持具有 startDate endDate 超过四年的谓词。我没有找到关于这个事实的任何官方文档,但在实践中,该方法似乎只是返回事件 endDate 或四年后 startDate ,以先到者为准。

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] 返回过去几个世纪的历史,因此,如果您创建一个以开始日期为开始日期的谓词,您可能会得到一个错误的答案。

[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.

最简单的解决方案是

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.

这篇关于为什么eventsMatchingPredicate返回nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆