6.14 Creating Dependency Between Operations

来源:互联网 发布:网络社会工程学是什么 编辑:程序博客网 时间:2024/06/05 20:40


在某个任务完成后才开始另一个任务

没什么好说的,上例子

- (void) firstOperationEntry:(id)paramObject{

    NSLog(@"First Operation - Parameter Object = %@", paramObject);

    NSLog(@"First Operation - Main Thread = %@", [NSThreadmainThread]);

    NSLog(@"First Operation - Current Thread = %@", [NSThreadcurrentThread]);

}

- (void) secondOperationEntry:(id)paramObject{

    NSLog(@"Second Operation - Parameter Object = %@", paramObject);

    NSLog(@"Second Operation - Main Thread = %@", [NSThreadmainThread]);

    NSLog(@"Second Operation - Current Thread = %@", [NSThreadcurrentThread]);

}


-(void)test6_14

{

   NSNumber *firstNumber = [NSNumbernumberWithInteger:111];

   NSNumber *secondNumber = [NSNumbernumberWithInteger:222];

    

   NSInvocationOperation *firstOperation;

   NSInvocationOperation *secondOperation;

   NSOperationQueue *operationQueue;

    

    firstOperation = [[NSInvocationOperationalloc] initWithTarget:self

                                                              selector:@selector(firstOperationEntry:)object:firstNumber];

    secondOperation = [[NSInvocationOperationalloc] initWithTarget:self

                                                               selector:@selector(secondOperationEntry:)object:secondNumber];

    [firstOperationaddDependency:secondOperation];

//    [firstOperation removeDependency:secondOperation];

    operationQueue = [[NSOperationQueuealloc] init];

    /* Add the operations to the queue */

    [operationQueueaddOperation:firstOperation];

    [operationQueueaddOperation:secondOperation];

    NSLog(@"Main thread is here");

    

}



输出:

2014-03-12 10:27:22.158 cookbook[505:a0b] Main thread is here

2014-03-12 10:27:22.158 cookbook[505:1403] Second Operation - Parameter Object = 222

2014-03-12 10:27:22.159 cookbook[505:1403] Second Operation - Main Thread = <NSThread: 0x8950130>{name = (null), num = 1}

2014-03-12 10:27:22.159 cookbook[505:1403] Second Operation - Current Thread = <NSThread: 0x8c917d0>{name = (null), num = 2}

2014-03-12 10:27:22.160 cookbook[505:1403] First Operation - Parameter Object = 111

2014-03-12 10:27:22.160 cookbook[505:1403] First Operation - Main Thread = <NSThread: 0x8950130>{name = (null), num = 1}

2014-03-12 10:27:22.161 cookbook[505:1403] First Operation - Current Thread = <NSThread: 0x8c917d0>{name = (null), num = 2}


显然firstOperation是在secondOperation执行完成后才开始执行的。这是通过[firstOperationaddDependency:secondOperation];这句实现的。

如果想取消这种依赖关系,则用 [firstOperationremoveDependency:secondOperation];






0 0
原创粉丝点击