【问题标题】:why eventsMatchingPredicate returns nil?为什么 eventsMatchingPredicate 返回 nil?
【发布时间】:2013-11-06 21:45:09
【问题描述】:

这是我的代码:

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。但我确实在日历上添加了事件。有什么可以告诉我代码是否有问题?

【问题讨论】:

    标签: ios cocoa-touch ekevent


    【解决方案1】:

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

    [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]];
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 刚刚进行了测试,eventStore 不为零。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2014-11-11
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 2011-06-26
        • 2015-08-30
        相关资源
        最近更新 更多