1. 程式人生 > >1.Block內部執行完才走後續的程式碼 2.多次請求完成才執行程式碼

1.Block內部執行完才走後續的程式碼 2.多次請求完成才執行程式碼

1.使用訊號量

    //先建立一個semaphore
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    __block NSMutableArray *modelArr = [[NSMutableArray alloc]init];
    
    DataBaseTool *tool = [DataBaseTool sharedInstance];
    [tool inDatabase:^(FMDatabase *db) {
        FMResultSet *set = [db executeQuery:@"select * from user_data where redid = ?",redid];
        while ([set next]) {
            UserModel *model = [[UserModel alloc]init];
            model.userid = [set stringForColumnIndex:1];
            model.redid = [set stringForColumnIndex:2];
            model.status = [set doubleForColumnIndex:3];
            [modelArr addObject:model];
        }
        [set close];
        //發出已完成的訊號
        dispatch_semaphore_signal(semaphore);
    }];
    
    //等待執行,不會佔用資源
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return modeler;

2.使用dispatch_group

dispatch_group_t downloadGroup = dispatch_group_create();
//成對出現 任務開始時
dispatch_group_enter(downloadGroup);
//成對出現 任務結束時
dispatch_group_leave(downloadGroup);
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
    
});