2013-08-24 130 views
0

我試圖按照this tutorial的EKEvent,但我在if (err = noErr) {當試圖保存

今年年初收到錯誤失敗是我的代碼:

#import "CalendarViewController.h" 
#import <EventKit/EventKit.h> 

@interface CalendarViewController() 

@end 

@implementation CalendarViewController 

-(IBAction) createEvent { 

EKEventStore *eventStore = [[EKEventStore alloc ] init]; 

EKEvent *event = [EKEvent eventWithEventStore:eventStore]; 

NSDate *startDate = [[NSDate alloc] init]; 
NSDate *endDate = [[NSDate alloc] init]; 

event.title = @"Title for new event"; 
event.startDate = startDate; 
event.endDate = endDate; 
event.allDay = YES; 

[event setCalendar: [eventStore defaultCalendarForNewEvents]]; 

NSError *err; 


[eventStore saveEvent:event span:EKSpanThisEvent error:&err]; 
if (err == noErr) { 

    UIAlertView *alert = [[UIAlertView alloc] 
          initWithTitle:@"Event Created" 
          message:@"How about that?" 
          delegate:nil 
          cancelButtonTitle:@"Okay" 
          otherButtonTitles:nil]; 

     [alert show]; 
     [alert release]; 
} 

[startDate release]; 
[endDate release]; 
[eventStore release]; 
} 

我是初學者,這是我的HSC的一部分,但我沒有得到它的正常工作。我真的很感激任何幫助。

回答

1

目前接受的答案有點誤導。

如果Cocoa中的方法返回BOOL且包含對NSError對象的間接引用,則必須在檢查錯誤對象之前檢查返回值 - 因爲只有當返回值爲NO時,錯誤對象才能保證爲有效。

NSError *err; 

BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent error:&err]; 
if (success) { 

    UIAlertView *alert = [[UIAlertView alloc] 
          initWithTitle:@"Event Created" 
          message:@"How about that?" 
          delegate:nil 
          cancelButtonTitle:@"Okay" 
          otherButtonTitles:nil]; 

     [alert show]; 
     [alert release]; 
} else { 
    if (!err) { 
     // If the event is not modified then the return is `NO` and there is no error 
     UIAlertView *alert = [[UIAlertView alloc] 
          initWithTitle:@"Event Unchanged" 
          message:@"The event wasn't modified, so there is nothing to save." 
          delegate:nil 
          cancelButtonTitle:@"Okay" 
          otherButtonTitles:nil]; 

     [alert show]; 
     [alert release]; 
    } else { 
     // The method was unsuccessful and there is a valid error 
     NSString *errorMessage = [NSString stringWithFormat:@" Unable to save because: %@", [err localizedDescription]; 
     UIAlertView *alert = [[UIAlertView alloc] 
          initWithTitle:@"Error!" 
          message:errorMessage" 
          delegate:nil 
          cancelButtonTitle:@"Okay" 
          otherButtonTitles:nil]; 

     [alert show]; 
     [alert release]; 
    } 
} 

比我實際上做的方式wordier一點,但你應該明白我的意思

相關問題