【问题标题】:Indicating to main thread that Async call for calendar access has been completed向主线程指示日历访问的异步调用已完成
【发布时间】:2014-11-26 06:49:24
【问题描述】:

我希望日历访问用户的 iPhone,因为我正在使用异步调用

__block NSMutableArray* someData;
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
    //We are going to fetch events from today to the next 1 year
    if (granted) {
        //Processing
        [someData addObject:@"Something Added"]
    }

}];

我基本上想做一些处理,然后向在另一个对象中执行的主线程发出信号,表明处理已经在 someData 上完成,它现在应该访问它。

我曾尝试将其包装在这样的调度组中

dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    calendarData = [calender returnCalenderEvents];
});

dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    NSLog(@"%@",calendarData);
});

但是由于调用是异步的,它仍然会在完成任何实际完成之前通知组完成。

基本上我怎样才能在异步调用上向主线程发出处理已完成的信号,获取结果并开始进行自己的处理

【问题讨论】:

  • 为什么不访问辅助线程中的主线程。然后只从这里通知。

标签: ios objective-c multithreading asynchronous grand-central-dispatch


【解决方案1】:

在 viewDidLoad 上添加通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(calendarPermissionGranted:) name:@"calendarProcessingCompleted" object:nil];

一旦授予日历权限,它将从此处发布通知。

 __block NSMutableArray* someData;
    [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        //We are going to fetch events from today to the next 1 year
        if (granted) {
            //Processing
            [someData addObject:@"Something Added"]

             dispatch_async(dispatch_get_main_queue(), ^{
                    //notify your class that processing has been done.
                  [[NSNotificationCenter defaultCenter]   postNotificationName:@"calendarProcessingCompleted" object:nil userInfo:nil];
              });
        }
}];

在方法中捕获它

-(void)calendarPermissionGranted:(NSNotification *)noti{

}

也许这就是你要找的。​​p>

【讨论】:

  • 我没有做任何与 UI 相关的操作,所以我不需要访问主线程。我只需要一种方法让视图控制器收到日历对象已完成处理的通知,现在您可以进行自己的处理了。
  • @WinCoder 我已经更新了我的答案,这可能会对你有所帮助,否则我不明白你想要做什么。
  • 啊,是的,我正在寻找这种东西,一个对象可以通知另一个对象,而无需任何形式的相互引用。
猜你喜欢
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多