繁体   English   中英

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

[英]Wait for an async task operation to finish and continue the current async task

我有两个在后台运行其代码的方法,而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
...

有没有办法命令这些方法的执行? 非常感谢您的帮助。

您已经在从后台线程调用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循环之后的块中,可能将其包装到主线程中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM