这是我的代码:
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。但我确实在日历上添加了事件。有谁能告诉我代码是否有问题吗?
根据这个答案 https://stackoverflow.com/a/8888550/704319 and 这个帖子 https://stackoverflow.com/q/9988843/704319, EKEventStore eventsMatchingPredicate:
不支持带有 a 的谓词startDate
and endDate
相差四年多。我找不到关于这一事实的任何官方文档,但实际上该方法似乎只返回事件endDate
或四年后startDate
, 以先到者为准。
[NSDate distantPast]
回报几个世纪前的日期 https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/clm/NSDate/distantPast,因此,如果您以此作为开始日期创建谓词,那么您几乎肯定会得到错误的答案。
最简单的解决方案是将您的代码更改为如下所示:
NSDate* fourYearsAgo = [NSDate dateWithTimeIntervalSinceNow:-1 * 60 * 60 * 24 * 365 * 4];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fourYearsAgo endDate:[NSDate date] calendars:@[cal]];
如果这对你不起作用,你要么必须找到一种方法来更明智地选择你的界限,要么创建连续的四年谓词,直到找到你想要的东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)