我正在处理一个从特定iOS日历中获取事件的应用。当那个日历是空的时候,我当然会得到一个致命的零错误。
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 :(得分: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)")
}
}
}