There are three operation classes in Foundation Framework(NSOperation
, NSInvocationOperation
and NSBlockOperation
).
I already read the concurrency programming guide but I did't understand exactly what is the difference between these three classes. Please help me.
An operation that manages the concurrent execution of one or more blocks.
An abstract class that represents the code and data associated with a single task.
NSBlockOperation
exectues a block. NSInvocationOperation
executes a NSInvocation
(or a method defined by target, selector, object). NSOperation
must be subclassed, it offers the most flexibility but requires the most code.
NSBlockOperation and NSInvocationOperation are both subclasses of NSOperation. They are provided by the system so you don't have to create a new subclass for simple tasks.
Using NSBlockOperation and NSInvocationOperation should be enough for most tasks.
Here is a code example for the use of all three that do exactly the same thing:
// For NSOperation subclass
@interface SayHelloOperation : NSOperation
@end
@implementation SayHelloOperation
- (void)main {
NSLog(@"Hello World");
}
@end
// For NSInvocationOperation
- (void)sayHello {
NSLog(@"Hello World");
}
- (void)startBlocks {
NSBlockOperation *blockOP = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Hello World");
}];
NSInvocationOperation *invocationOP = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(sayHello) object:nil];
SayHelloOperation *operation = [[SayHelloOperation alloc] init];
NSOperationQueue *q = [[NSOperationQueue alloc] init];
[q addOperation:blockOP];
[q addOperation:invocationOP];
[q addOperation:operation];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With