7.13. Creating Dependency Between Operations
Problem
You want to start a certain task only after another task has finished executing.
Solution
If operation B has to wait for operation A before it can run
the task associated with it, operation B has to add operation A as its
dependency using the addDependency:
instance method of NSOperation
, as
shown here:
[
self
.
firstOperation
addDependency
:
self
.
secondOperation
];
Both the firstOperation
and the secondOperation
properties
are of type NSInvocation
Operation
, as we will see in this recipe’s
Discussion. In this example code,
the first operation will not be executed by the operation queue until
after the second operation’s task is finished.
Discussion
An operation will not start executing until all the operations on which it depends have successfully finished executing the tasks associated with them. By default, an operation, after initialization, has no dependency on other operations.
If we want to introduce dependencies to the example code described
in Recipe 7.12,
we can slightly modify the application delegate’s
implementation and use the add
Dependency:
instance method to have the first
operation wait for the second operation:
#import "AppDelegate.h"
@interface
AppDelegate
()
@property
(
nonatomic
,
strong
)
NSInvocationOperation
*
firstOperation
;
@property
(
nonatomic
,
strong
)
NSInvocationOperation
*
secondOperation
;
@property
(
nonatomic
,
strong
)
NSOperationQueue
*
operationQueue
;
@end
@implementation
AppDelegate
-
(
void
)
firstOperationEntry:
(
id ...
Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.