6.14 Creating Dependency Between Operations

本文通过一个具体的示例展示了如何使用 NSOperation 和 NSOperationQueue 在 iOS 开发中管理任务间的依赖关系,确保一个操作在另一个操作完成后才开始执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

没什么好说的,上例子

- (void) firstOperationEntry:(id)paramObject{

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

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

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

}

- (void) secondOperationEntry:(id)paramObject{

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

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

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

}


-(void)test6_14

{

    NSNumber *firstNumber = [NSNumber numberWithInteger:111];

    NSNumber *secondNumber = [NSNumber numberWithInteger:222];

    

    NSInvocationOperation *firstOperation;

    NSInvocationOperation *secondOperation;

    NSOperationQueue *operationQueue;

    

    firstOperation = [[NSInvocationOperation alloc] initWithTarget:self

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

    secondOperation = [[NSInvocationOperation alloc] initWithTarget:self

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

    [firstOperation addDependency:secondOperation];

//    [firstOperation removeDependency:secondOperation];

    operationQueue = [[NSOperationQueue alloc] init];

    /* Add the operations to the queue */

    [operationQueue addOperation:firstOperation];

    [operationQueue addOperation: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执行完成后才开始执行的。这是通过[firstOperation addDependency:secondOperation];这句实现的。

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






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值