Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between NSInvocationOperation and NSBlockOperation

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.

like image 999
MobileDev Avatar asked Sep 05 '13 09:09

MobileDev


People also ask

What is Nsblockoperation?

An operation that manages the concurrent execution of one or more blocks.

What is NSOperation?

An abstract class that represents the code and data associated with a single task.


1 Answers

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];
}
like image 96
Matthias Bauch Avatar answered Sep 20 '22 17:09

Matthias Bauch