What is the difference between NSInvocationOperation and NSBlockOperation

前端 未结 3 663
臣服心动
臣服心动 2021-02-04 06:11

There are three operation classes in Foundation Framework(NSOperation, NSInvocationOperation and NSBlockOperation).

I already

3条回答
  •  一向
    一向 (楼主)
    2021-02-04 06:44

    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];
    }
    

提交回复
热议问题