2015-03-27 2 views
-1

Я работаю над приложением, которое получает события из определенного календаря iOS. Когда этот календарь пуст, я, конечно, получаю смертельную ошибку.Проверка на нуль в EKCalendar

let calendar = calendarWithTitle("Personal Trainer's Tool", 
      type: EKCalendarTypeCalDAV, 
      source: icloudSource!, 
      eventType: EKEntityTypeEvent) 

/* Create the predicate that we can later pass to the event store in order to fetch the events */ 
     let searchPredicate = eventStore.predicateForEventsWithStartDate(
      startDate, 
      endDate: endDate, 
      calendars: [calendar!]) 

/* Fetch all the events that fall between the starting and the ending dates */ 
     events = eventStore.eventsMatchingPredicate(searchPredicate) as [EKEvent] //Error on this line 


if events.count == 0 { 
       println("No events could be found") 
      } else { 

       // Go through all the events and print them to the console 
       for event in events{ 
        println("Event title = \(event.title)") 
        println("Event start date = \(event.startDate)") 
        println("Event end date = \(event.endDate)") 
       } 
      } 

«календарь» в моем searchPredicate является EKCalendar, как это должно быть, но я не знаю, как проверить, если она пуста, прежде чем разрешить searchPredicate выполнить, чтобы избежать фатальной ошибки. Кто-нибудь знает, как решить эту проблему?

Благодаря

ответ

0

Вы можете использовать опциональный связывания:

let calendar = calendarWithTitle("Personal Trainer's Tool", 
    type: EKCalendarTypeCalDAV, 
    source: icloudSource!, 
    eventType: EKEntityTypeEvent) 

/* Create the predicate that we can later pass to the event store in order to fetch the events */ 
let searchPredicate = eventStore.predicateForEventsWithStartDate(
    startDate, 
    endDate: endDate, 
    calendars: [calendar!]) 

/* Fetch all the events that fall between the starting and the ending dates */ 
if let events = eventStore.eventsMatchingPredicate(searchPredicate) as? [EKEvent] { 


    if events.count == 0 { 
     println("No events could be found") 
    } else { 

     // Go through all the events and print them to the console 
     for event in events{ 
      println("Event title = \(event.title)") 
      println("Event start date = \(event.startDate)") 
      println("Event end date = \(event.endDate)") 
     } 
    } 
} 
Смежные вопросы