TheObjCGuy TheObjCGuy - 6 months ago 13
iOS Question

NSoperation reverse dependencies

In one of my apps i have a NSOperationQueue and some subclass of NSOperations.
I've added some dependencies so, the operation A not start until operation B finish.

I need to cancel the operation A if the operation B fails, but from inside the operation B i don't have any list of operation who dependes on the current operation.

I will try to add some weak properties on my subclass, like

@property (nonatomic, weak) NSArray *dependsOnMe;


but i'm afraid to generate some strange loop.

thanks

Answer

Theres a bit of missing info here. Like when you construct B , do you also construct A?

Is there a need to do this? Why not construct A on the successful completion of B?

You could use use a delegate protocol if its a one to one dependancy from B to A

@protocol DependantOperationCompletion <NSObject>

-(void)operationDidFail;

@end

@interface BOperation

@property (weak) id<DependantOperationCompletion> delegate;

@end

and

@interface AOperation:NSOperation <DependantOperationCompletion> 

...

@end

then when you construct the operations set up A as a delegate of B

bOpInstance.delegate = aOpInstance;

Alternatively use the "Shout out the window" approach and post a notification if B fails. A listens for the notification.

within B...

-(void)handleFailure
{
    [[NSNotificationCenter defaultCenter] postNotificationName:BTypeOpDidFailNotification object:self userInfo:someInfoOrNil]

}

within A...

-(void)setupWithBOp:(BOperation *)binstance
{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ohNoBHazFailed:) name:BTypeOpDidFailNotification object:binstance];

}

Remember to remove A as observer on dealloc

Comments