Thursday, September 17, 2009

Making NSOperation look like GCD

For my last article I posted, I realized that when coming up with code examples that I had been writing examples with NSOperation using it the same way I had been writing code with NSOperation before, namely creating a NSOperation object and adding it to the Queue. However, I overlooked that NSOperationQueue in 10.6 contains a -addOperationWithBlock: method. Using that you could indeed write code with NSOperationQueue that doesn't look too dissimilar from the GCD API like so
//GCD Recursive Decomposition
dispatch_queue_t queue = dispatch_queue_create("com.App.Task",NULL);
 
dispatch_async(queue,^{
	CGFloat num = [self doSomeMassiveComputation];
 
	dispatch_async(dispatch_get_main_queue(),^{
		[self updateUIWithNumber:num];
	});
});
 
//NSOperationQueue Recursive Decomposition
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setName:@"com.App.Task"];
 
[queue addOperationWithBlock:^{
	CGFloat num = [self doSomeMassiveComputation];
 
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		[self updateUIWithNumber:num];
	}];
}];
The only downside to this being that you can't get a reference to the newly created NSOperation object that it creates for you and change it before adding it to the queue, but this creates an Objective-C style way for accomplishing the same thing the GCD API does with only 1 extra line of code.

1 comment:

  1. Anonymous1:37 PM

    There's also -[NSBlockOperation blockOperationWithBlock:], which lets you create an NSBlockOperation independently from adding it to a queue.

    This allows you to work with NSOperation similarly to how you would work with GCD, but also use KVO to track start/completion, and take advantage of NSOperation's dependency mechanism.

    ReplyDelete