如何等待包含块的方法执行

时间:2013-08-16 07:37:22

标签: iphone ios

我处于需要等待方法执行然后只执行前进的情况我尝试了cfrunlooprun和

  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);


    dispatch_async(queue, ^{
              [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
     {

但这并没有帮助我,我的代码在下面

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate 

    toDate:(NSDate*)lastDate{

        [self fatchAllEvent];// this method contain block it takes 1 second to get executed and events array get filled from that block

        NSLog(@"all event %@",events); it shows null here cuse blocked has not executed yet

        [self generateRandomDataForStartDate:startDate endDate:lastDate]; this method need events array but as there is no data so nothing happens 


        return self.dataArray;

    }

我怎么能等到fatchAllEvent方法执行,然后才执行处理

1 个答案:

答案 0 :(得分:1)

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();

// Add a task to the group
dispatch_group_async(group, queue, ^{
    [self method1:a];
});

// Add another task to the group
dispatch_group_async(group, queue, ^{
    [self method2:a];
});

// Add a handler function for when the entire group completes
// It's possible that this will happen immediately if the other methods have already finished
dispatch_group_notify(group, queue, ^{
     [self methodFinish]
});

Dispatch groups are ARC managed. They are retained by the system until all of their blocks run, so their memory management is easy under ARC.

See also dispatch_group_wait() if you want to block execution until the group finishes.