当我尝试运行此代码时,我收到EXEC_BAD_ACCESS错误,并且用户未允许访问日历。 requestAccessToEntityType是否在单独的线程上运行,如果是这样的话,我如何访问主线程以显示UIAlertView?
EKEventStore *store = [[EKEventStore alloc] init];
if ([store respondsToSelector:@selector(requestAccessToEntityType:completion:)])
{
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if ( granted )
{
[self readEvents];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Denied Access To Calendar"
message:@"Access was denied to the calendar, please go into settings and allow this app access to the calendar!"
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil,
nil];
[alert show];
}
}];
}
答案 0 :(得分:3)
根据docs for requestAccessToEntityType
当用户点击授予或拒绝访问时,完成处理程序 将在任意队列上调用。
所以,是的,它可能在与UI不同的线程上。您只能从主GUI线程中发出警报。
查看performSelectorOnMainThread
。更多信息请访问:Perform UI Changes on main thread using dispatch_async or performSelectorOnMainThread?
答案 1 :(得分:2)
您的应用程序崩溃的原因是因为您尝试处理GUI元素,即后台线程中的UIAlertView,您需要在主线程上运行它或尝试使用调度队列
使用Dispatch Queues
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//show your UIAlertView here... or any GUI stuff
});
或者你可以像这样在主线程上显示GUI元素
[alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
您可以在此link
上了解有关在线程上使用GUI元素的更多详细信息