I am currently exploring the possibilities of blocks, I read apples docs more than ten times), but I can not understand the behavior of blocks in the blog examples and in my code. I know about the __block modifier. So please look at a few of my examples and tell me why this works or not:
1) Doesn't work. I need a __ block, because I want to change the object. And I keep it (right?), And on the blogs I got scared, keeping the cycle myself. This is true?
NSDictionary *result = nil; dispatch_async(queue, ^{ result = [self sendRequest:apiRequest]; });
2) Doesn't work. I do not understand about the scope variable dispatch_async (dispatch_get_main_queue (), ^ {}) ;. Does he see all local variables in the main thread or a separate block from the main thread, but is called in the main thread? For example dispatch_async (dispatch_get_main_queue () ^ {}); copies all local variables to dispatch_async (queue, ^ {}); and switches the semaphore to the main thread.
NSDictionary *result = nil; dispatch_async(queue, ^{ NSDictionary *data = [self sendRequest:apiRequest]; dispatch_async(dispatch_get_main_queue(), ^{ result=[data retain]; }); });
3) And examples from Stanford's blogs and course, which especially confuse me because they work.
- (void)viewWillAppear:(BOOL)animated { dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL); dispatch_async(downloadQueue, ^{ NSData *imageData = [NSData dataWithContentsOfURL:networkURL]; dispatch_async(dispatch_get_main_queue(), ^{ UIImage *image = [UIImage imageWithData:imageData]; self.imageView.image = image; self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height); οΏΌ self.scrollView.contentSize = image.size; }); }); dispatch_release(downloadQueue); }
I donβt understand, because at first they did not mention __block for themselves in articles and lessons, secondly, this code modified the variables, but through the properties and complier did not swear that the variables arent assigned and the properties change the link, not the value. The final is working. Thanks in advance.