Work with blocks, completion handlers, dispatch_async vs dispatch_sync

I am fetching data online in a stream, and I want to do something right after the block is executed.

Here is my code:

- (IBAction)refresh:(UIBarButtonItem *)sender { NSLog(@"checking"); [self editToolbar]; dispatch_queue_t fetchQ = dispatch_queue_create("Refreshing", NULL); dispatch_async(fetchQ, ^{ [self setupFetchedResultsController]; [self fetchImonggoItemsDataIntoDocument: self.itemDatabase]; }); dispatch_release(fetchQ); NSLog(@"done checking"); //do something here } 

The fact is that dispatch_async immediately returns and "completes the check" immediately, even before the execution of the block. How to solve this?

+4
source share
2 answers

I think this is an architectural problem. Tasks:

  • editing toolbar
  • fetchImonggoItemsDataIntoDocument
  • do something else

If this needs to be done in order, then I do not quite understand the use of blocks or queues; just run the instructions one by one and you will be installed.

Otherwise, alternative # 1 would be to use dispatch_sync rather than dispatch_async . Again, I'm not quite sure what the use of the queue will be, but there is one.

Alternative # 2 would be to use a callback from a block. Sort of:

 - (IBAction)refresh:(UIBarButtonItem *)sender { NSLog(@"checking"); [self editToolbar]; dispatch_queue_t fetchQ = dispatch_queue_create("Refreshing", NULL); dispatch_async(fetchQ, ^{ [self setupFetchedResultsController]; [self fetchImonggoItemsDataIntoDocument: self.itemDatabase]; [self doneChecking]; // <-- NOTE! call the callback }); dispatch_release(fetchQ); } // NOTE! refresh: has been split up into two methods - (void)doneChecking: NSLog(@"done checking"); //do something here } 
+4
source

As others have said, this is probably what you need.

 NSArray *items = [iMonggoFetcher fetchImonggoData:IMONGGO_GENERIC_URL_FOR_PRODUCTS withFormat:@"json" withDateRangeArgs:args]; [document.managedObjectContext performBlock:^{ for (NSDictionary *itemInfo in items){ [Product productWithImonggoInfo:itemInfo inManagedObjectContext:document.managedObjectContext]; } // Put here what you need :) }]; 
+1
source

Source: https://habr.com/ru/post/1399115/


All Articles