iOS:事件未保存。需要帮助调试

时间:2014-10-28 08:47:29

标签: ios xcode

以下是addEvent操作的完整代码。

- (IBAction)addEventBtnPressed:(id)sender
{
    EKEvent *myEvent = [EKEvent eventWithEventStore:self.eventStore];
    myEvent.title = self.eventTitle.text;
    myEvent.startDate = self.eventStartDate;
    myEvent.endDate = self.eventEndDate;
    myEvent.allDay = NO;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMMM dd hh:mma"];
    NSString *startTestDate = [dateFormatter stringFromDate:self.eventStartDate];
    NSString *endTestDate = [dateFormatter stringFromDate:self.eventEndDate];
    NSLog(@"Test title String:%@", myEvent.title);
    NSLog(@"Test Start Date String:%@", startTestDate);
    NSLog(@"Test Start Date String:%@", endTestDate);

    [myEvent setCalendar:[self.eventStore defaultCalendarForNewEvents]];
    NSError *err;

    [self.eventStore saveEvent:myEvent span:EKSpanThisEvent error:&err];

    if (err == noErr) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Event Created"
                              message:@"Yay!?"
                              delegate:nil
                              cancelButtonTitle:@"Okay"
                              otherButtonTitles:nil];
        [alert show];
    }
}

日志:

2014-10-28 04:44:18.881 Calendar[2668:1628432] Test title String:jtjtjtjrj
2014-10-28 04:44:18.882 Calendar[2668:1628432] Test Start Date String:October 30 12:00AM
2014-10-28 04:44:18.882 Calendar[2668:1628432] Test Start Date String:October 30 01:00AM

在我看来代码真的没什么问题,而且我不确定为什么在我查看常规日历时事件没有被保存。经过几个小时的尝试,我很难过。任何帮助将不胜感激。

更新

我在viewDidLoad上调用setDateLabels()方法,一旦我停止调用此方法,就会再次正确添加事件。我很困惑为什么这会产生任何影响。代码如下所示:

- (void)setDateLables:(NSDate*)firstSelectedDate
{
    [self.datePicker setDate:firstSelectedDate];
    NSDate *startDate = firstSelectedDate;
    NSTimeInterval anHourAfter = 1 * 60 * 60;
    NSDate *endDate = [startDate dateByAddingTimeInterval:anHourAfter];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMMM dd hh:mma"];
    self.eventStartDate = startDate;
    self.eventEndDate = endDate;
    self.startDateLabel.text = [dateFormatter stringFromDate:startDate];
    self.endDateLabel.text = [dateFormatter stringFromDate:endDate];
}

我怀疑NSDate *endDate = [startDate dateByAddingTimeInterval:anHourAfter];有一些意想不到的行为。任何帮助将不胜感激!

我将其固定为一行代码: 只要我摆脱[self.datePicker setDate:firstSelectedDate];,我就可以成功添加事件。我添加了这一行来在所选日期启动datepicker,它在视觉上成功运行,但它阻止了事件的添加。这背后可能是什么原因?

1 个答案:

答案 0 :(得分:0)

很可能err不等于noErr。 NoErr设置为什么?

无论如何,在不知道saveEvent的实现的情况下,如果没有错误,它应该保持不变,因此你要检查:

if (!err) {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Event Created"
                          message:@"Yay!?"
                          delegate:nil
                          cancelButtonTitle:@"Okay"
                          otherButtonTitles:nil];