iOS編程Cookbook第19章最後一個例子不能正常工作的解決辦法
在Cookbook的第19章的11節中所要解決的是在App中顯示iOS內建的日曆編輯檢視的問題.
例子代碼是選擇迄今為止1年前的第一個找到的日曆事件,然後將其顯示在日曆編輯檢視中.
日曆編輯檢視控制器是EKEventEditViewController的執行個體對象,按照書上的說明,其有一個event執行個體變數,如果在顯示該控制器之前不對其賦值,即其值為nil則出現的是一個新增Event的View,如果對其賦值一個特定的Event對象,則顯示的是編輯該Event的視圖.
具體代碼如下:
-(void)displayEventEditController{ EKSource *icloudSource = [self sourceInEventStore:self.eventStore sourceType:EKSourceTypeCalDAV sourceTitle:@"iCloud"]; if (!icloudSource) { NSLog(@"iCloud source don't exist!!!"); return; } NSSet *calendars = [icloudSource calendarsForEntityType:EKEntityTypeEvent]; NSTimeInterval OneYear = 1*365*24*60*60; NSDate *startDate = [[NSDate date]dateByAddingTimeInterval:-OneYear]; NSDate *endDate = [NSDate date]; NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:calendars.allObjects]; NSArray *events = [self.eventStore eventsMatchingPredicate:predicate]; if (events.count > 0) { EKEvent *event = events.firstObject; EKEventEditViewController *controller = [EKEventEditViewController new]; controller.event = event; controller.editViewDelegate = self; [self.navigationController presentViewController:controller animated:YES completion:nil]; }}
但是在實際運行該App時發現,如果不修改選擇Done或者Cancel,則沒有問題.只要對原有Event進行修改再儲存,都會顯示錯誤:
Calendar: unable to save: (null)
但是從字面上不知道是神馬地方出錯了!
同樣的Event從iOS內建的日曆App中修改是沒有問題的.
後來尋找了文檔,其中有說明:必須設定日曆編輯檢視控制器的eventStore執行個體變數為正確的stroe對象,否則不能儲存.
於是將上述代碼在顯示控制器前位置插入以下一行即可:
controller.eventStore = self.eventStore;
再次運行App,現在可以正常儲存Event了 ;)