等待异步任务操作完成并继续当前的异步任务

时间:2014-03-31 18:10:17

标签: ios grand-central-dispatch dispatch-async

我有两种在后台运行代码的方法,而method1按如下方式触发method2:

+(void)insertAllDataInDatabase{
    NSLog(@"1");        
    NSString *url=@"http://localhost/kalimat/get_all_artists.php";        
    //NSLog(@"url %@",url);        
    NSURL *urlChannels= [ NSURL URLWithString:url];                
    NSURLRequest *request = [NSURLRequest requestWithURL:urlChannels];                
    AFJSONRequestOperation *operation = [AFJSONRequestOperation 
        JSONRequestOperationWithRequest:request 
                                success:^(NSURLRequest *request, 
                                          NSHTTPURLResponse *response, 
                                          id JSON) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) 
        {
            NSMutableArray *arrayOfJson=JSON;
            for (int i=0; i<[arrayOfJson count]; i++) {
                NSLog(@"2");
                NSMutableDictionary *songDico=[arrayOfJson objectAtIndex:i];
                NSString *artist=[songDico objectForKey:@"artist"];
                [self getArtistSongs:artist];
            }
        });
        NSLog(@"6");

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
                NSError *error, id JSON) {
        //DLog(@"Request Failure Because %@",[error userInfo]);
    }];
    [operation start];
}

+(void)getArtistSongs:(NSString*)artist {
    NSLog(@"3");
    LKDBHelper* globalHelper = [LKDBHelper getUsingLKDBHelper];
    NSMutableArray *arrayOfSongs=[[NSMutableArray alloc]init];
    artist = [artist stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //DLog(@"artisttt %@",artist);
        NSString *url=[NSString stringWithFormat:@"%@?artist=%@", @"http://localhost/kalimat/get_kalimat.php",artist];
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
        //NSLog(@"url %@",url);
        NSURL *urlChannels= [ NSURL URLWithString:url];
        NSURLRequest *request = [NSURLRequest requestWithURL:urlChannels];
        [LKDBHelper clearTableData:[Song class]];
        AFJSONRequestOperation *operation =
        [AFJSONRequestOperation JSONRequestOperationWithRequest:request
            success:^(NSURLRequest *request,
                      NSHTTPURLResponse *response,
                      id JSON) {
                NSMutableArray *arrayOfJson=JSON;
                for (int i=0; i<[arrayOfJson count]; i++) {
                    NSLog(@"4");
                    NSMutableDictionary *songDico=[arrayOfJson objectAtIndex:i];
                    DCKeyValueObjectMapping *parser = [DCKeyValueObjectMapping mapperForClass: [Song class]];
                    Song *song = [parser parseDictionary:songDico];
                    song.artist=artist;
                    [arrayOfSongs addObject:song];
                    //DLog(@"inserting...");
                    [globalHelper insertToDB:song];
                    //DLog(@"getting lyrics");
                    //[self getLyricsWhereArtist:artist andSong:song.song];
                    //[[NSNotificationCenter defaultCenter] postNotificationName:@"AllArtistsSongs" object:arrayOfSongs];
                }
                NSLog(@"5");
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
                        NSError *error, id JSON) {
                DLog(@"Request Failure Because %@",[error userInfo]);
            }];
        [operation start];
    });
}

基于NSLogs,我希望:

1
2
3
4
4
4
4
...
5
6

但我有:

1
6
2
3
2
3
2
3
2
3
...

有没有办法订购这些方法的执行? 非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您已经从后台线程调用了getArtistSongs:。如果您希望这些按顺序运行,只需从该方法中删除dispatch_async调用即可。您还需要同步发出这些请求;我还没有使用AFNetworking,所以我不知道它是否可用或如何使用。

这可以在不阻塞主线程的情况下工作,因为您对getArtistSongs:的调用来自后台线程上运行的块:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){

    // All this code runs in the background.

    NSMutableArray *arrayOfJson=JSON;
    for (int i=0; i<[arrayOfJson count]; i++) {

        NSLog(@"2");

        NSMutableDictionary *songDico=[arrayOfJson objectAtIndex:i];
        NSString *artist=[songDico objectForKey:@"artist"];

        [self getArtistSongs:artist];
    }

    // All code above runs in the background.

});

6当然,仍然会在1之后立即打印。如果你需要代码最后运行,它会进入块内,在songDiscos的for循环之后,可能在dispatch_async中包含到主线程中。

相关问题