Good pattern for Internet requests with Grand Central Dispatch?

前端 未结 4 1233
醉梦人生
醉梦人生 2021-02-04 11:54

I\'m currently using synchronous ASIHTTPRequest with GCD queues to download data from the Internet, then parse the response data with JSONKit. What do you think about this patte

4条回答
  •  深忆病人
    2021-02-04 12:15

    So you replaced this

    - (void)doDownload {
        NSURL *url = [NSURL URLWithString:@"http://foobar.com"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        connection = [[NSURLConnection alloc] initWithRequest:aURLRequest delegate:self];
        receivedData = [[NSMutableData data] retain];
    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [_receivedData appendData:data];
    }
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        NSArray *array = [_receivedData objectFromJSONDataWithParseOptions:JKParseOptionLooseUnicode];
        callbackBlock(array);       
    }
    

    with this -

    - (void)doDownload {
        NSURL *url = [NSURL URLWithString:@"http://foobar.com"];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
        dispatch_async(queue, ^(void) {
            [request startSynchronous];
            NSArray *array = [[request responseData] objectFromJSONDataWithParseOptions:JKParseOptionLooseUnicode];
    
            // Callback on the main queue to update UI.
            dispatch_async(dispatch_get_main_queue(), ^(void) {
                callbackBlock(array);
            });
        });
    }
    

    and 10,000+ lines of code from ASIHTTPRequest.

    What has it got you?

    NSURLConnection is fully asynchronous, uses GCD, caches, automatic zip/unzip, etc, etc..

    For that reason, and going solely on the (possibly incomplete) information you provided, i'd say that it was a really awful piece of code.

    Of course, context is everything - and you may have a really, really, really good reason for reimplementing the already existing functionality of Library code provided by Apple.

提交回复
热议问题