Domanda

URL nella matrice sono chiamati uno dopo l'altro. Non dovrebbe essere chiamato tutto in una volta, come nsoperationqueue? Please help me qui, grazie

  - (void) allTasksDone {
    NSLog(@"DONE");
  }

  - (void) callMultiple {
    dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
    dispatch_group_t group = dispatch_group_create();
    NSArray *urls = [NSArray arrayWithObjects:
                     @"http://www.a.com",
                     @"http://www.b.com",
                                     @"http://www.c.com",

                     nil];

    for (NSString *url in urls) {


        dispatch_group_async(group, myQueue, ^{


            NSLog(url);

            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
            NSHTTPURLResponse *response = NULL;
            NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];


            NSLog(@"COMPLETE");

        });
    }

    dispatch_group_notify(group, myQueue, ^{
        [self allTasksDone];
    });

  }


  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {        

     [self callMultiple];

     [self.window makeKeyAndVisible];

     return YES;
  }
È stato utile?

Soluzione

dispatch_queue_create crea coda FIFO. Ci vuole blocchi uno per uno dalla coda nello stesso ordine in tema sono stati aggiunti. Se si desidera eseguire blocchi contemporaneamente è possibile creare diverse code per ogni blocco o di ottenere l'uso di una delle code globali.

dispatch_queue_t dispatch_get_global_queue(
   long priority,
   unsigned long flags);

Ci sono 3 le code globali, che si distinguono in base alla priorità.

enum {
   DISPATCH_QUEUE_PRIORITY_HIGH = 2,
   DISPATCH_QUEUE_PRIORITY_DEFAULT = 0,
   DISPATCH_QUEUE_PRIORITY_LOW = -2,
};

Queste le code non aspetta per il completamento del blocco precedente. Così i vostri download saranno eseguiti contemporaneamente.

Altri suggerimenti

Innanzitutto, no, asincrona () non garantisce esecuzione asincrona dei blocchi. Che succederà solo se un determinato blocco è bloccato in attesa che succeda qualcosa. GCD poi girare su un altro thread.

Tuttavia, se il sistema è già relativamente caricato, GCD non sta per girare un nuovo thread per fare un po 'di lavoro se il lavoro è già in corso.

In secondo luogo, non v'è alcun motivo per spingere NSURLRequests in secondo piano tramite GCD. NSURLRequest supporta download asincrono già.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top