Skip to content

Concurrency programming

Maciej Walczynski edited this page Oct 21, 2013 · 11 revisions

Blocks

  1. Create a simple block and invoke it,
  2. Create a block with params and invoke it
  3. Show how block (__block) variables work
  4. show how to avoid self strong referencing
  5. show how to pass blocks to methods
- (void) runBlock:(void (^)(NSNumber* number, NSString* text))completionBlock;
  1. show typedefing
typedef void (^ImageCompletionBlock)(UIImage *);  
typedef void (^ActionBlock)();

Grand Central dispatch

  1. Use gcd to create a background task
  2. Create a dead lock
  3. Understand:
  • serial queues
  • global concurrent queues
  • main dispatch queue
  1. Singleton with GCD
+ (MyClass *)sharedInstance
{
    //  Static local predicate must be initialized to 0
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}
  1. Dispatch groups
dispatch_queue_t queue = dispatch_get_global_qeueue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
for(id obj in array)
    dispatch_group_async(group, queue, ^{
        [self doSomethingIntensiveWith:obj];
    });
dispatch_group_notify(group, queue, ^{
    [self doSomethingWith:array];
});
dispatch_release(group);

NSOperation queues

NSInvocationOperation

NSOperationQueue *queue = [NSOperationQueue new];
 
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
    selector:@selector(methodToCall)
    object:objectToPassToMethod];
 
[queue addOperation:operation];
[operation release];

NSBlockOperation

NSBlockOperation* theOp = [NSBlockOperation blockOperationWithBlock: ^{
    NSLog(@"Beginning operation.\n");
    // Do some work.
}];

NSOperation subclassing

Clone this wiki locally