如何在变量中隔离事件的标题/时间以在故事板上显示?

时间:2014-10-17 04:36:18

标签: objective-c ekevent

以下是我的问题的完整描述:我正在获取日历事件一整天(即今天)并将它们存储在一个数组中。如何从阵列中隔离下一个相关的(未通过的)事件的标题和时间,将它们作为标签单独显示? 这是我的代码:

//Load Calendar Events
    EKEventStore *store = [[EKEventStore alloc] init];

    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,
                                                                    NSError *error) {
        if (granted) {
        NSLog(@"User has granted permission");
        // Get the appropriate calendar
        NSCalendar *calendar = [NSCalendar currentCalendar];

        // Create the start date components
        NSDateComponents *beginDayComponents = [[NSDateComponents alloc] init];
        beginDayComponents.day = 0;
        NSDate *todayStart = [calendar dateByAddingComponents:beginDayComponents
                                                      toDate:[NSDate date]
                                                     options:0];

        // Create the end date components
        NSDateComponents *endDayComponents = [[NSDateComponents alloc] init];
        endDayComponents.day = 0;
        NSDate *todayEnd = [calendar dateByAddingComponents:endDayComponents
                                                           toDate:[NSDate date]
                                                          options:0];

        // Create the predicate from the event store's instance method
        NSPredicate *predicate = [store predicateForEventsWithStartDate:todayStart
                                                                endDate:todayEnd
                                                              calendars:nil];

        // Fetch all events that match the predicate
        NSArray *events = [store eventsMatchingPredicate:predicate];
        NSLog(@"Here are the events in the array, %@", events);



        } else {
            NSLog(@"User has not granted permission");
        }
    }];

提前致谢,祝你有个美好的一天!

1 个答案:

答案 0 :(得分:1)

正如Apple在其EKEventStore文档中所述,您必须先对数组进行排序,以便下一个待处理事件位于索引0处。

  

注意:从日历数据库中检索事件不会   必须按时间顺序返回事件。排序数组   按日期EKEvent对象,在数组上调用sortedArrayUsingSelector:   为compareStartDateWithEvent:方法提供选择器。

我建议你只需在数组索引0处选择EKEvent-Object并从中读取属性并将其设置在标签上。

EKEvent *event = [events objectAtIndex:0];
yourTitleLabel.text = event.text;

NSDateFormatter *formatter =  [[NSDateFormatter alloc] init];
formatter.dateformat = @"dd.MM HH:mm";
yourDateLabel.text = [formatter stringFromDate:event.startDate];

修改 您可以像这样对数组事件进行排序:

events = [events sortedArrayUsingSelector:@selector(compareStartDateWithEvent:)];

要使其正常工作,您必须导入 EventKit / EventKit.h