SORU
23 ŞUBAT 2012, PERŞEMBE


NSURLConnection sendAsynchronousRequest:sıra:completionHandler: birden fazla yapma istekleri bir satırda?

HarikaNSURLConnection's sendAsynchronousRequest:queue:completionHandler: yöntem kullanıyorum. Ama, ben şimdi bir satırda birden çok istemenize gerek yoktur.

Nasıl hala bu büyük asychronous yöntemi kullanarak bunu yapabilir miyim?

CEVAP
23 ŞUBAT 2012, PERŞEMBE


Bu istediğiniz davranış bağlı olarak, bunu yapmanın pek çok yolu var.

Zaman uyumsuz istekleri bir grup aynı anda gönderebilirsiniz, tamamlanmış istekleri sayısını izlemek ve bitti hepsi bir şeyler yapın:

NSInteger outstandingRequests = [requestsArray count];
for (NSURLRequest *request in requestsArray) {
    [NSURLConnection sendAsynchronousRequest:request 
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        [self doSomethingWithData:data];
        outstandingRequests--;
        if (outstandingRequests == 0) {
            [self doSomethingElse];
        }
    }];
}

Bloklar birbirine zincir:

NSMutableArray *dataArray = [NSMutableArray array];    
__block (^handler)(NSURLResponse *response, NSData *data, NSError *error);

NSInteger currentRequestIndex = 0;
handler = ^{
    [dataArray addObject:data];
    currentRequestIndex  ;
    if (currentRequestIndex < [requestsArray count]) {
        [NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:currentRequestIndex] 
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:handler];
    } else {
        [self doSomethingElse];
    }
};
[NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:0] 
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:handler];

Ya da eşzamanlı olarak ansynchronous bir blok içinde tüm istekleri yapabilirsiniz:

dispatch_queue_t callerQueue = dispatch_get_current_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL);
    dispatch_async(downloadQueue, ^{
        for (NSRURLRequest *request in requestsArray) {
            [dataArray addObject:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]];
        }
        dispatch_async(callerQueue, ^{
            [self doSomethingWithDataArray:dataArray];
        });
    });
});

Eğer hata kontrolü eklemek gerekir bunlardan herhangi birini kullanıyorsanız, P. S..

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • BiGSH0TROB

    BiGSH0TROB

    7 NİSAN 2011
  • filmurfreakur

    filmurfreaku

    29 Mart 2007
  • LavcoPriceTech

    LavcoPriceTe

    21 AĞUSTOS 2010