开发者

NSOperation finished

I have an NSOperation running in a NSOperationQueue. The NSOperation downloads some data and parses it into NSDictionary. How do I know when the NSOperation has finished and get that dictionary? Than开发者_运维技巧ks.


You can also use NSOperation's - (void)setCompletionBlock::

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Doing something...");
}];

[operation setCompletionBlock:^{
    NSLog(@"Doing something once the operation has finished...");
}];

[queue addOperation:operation];

Much more detail here.


If the block of code that needs to know when the operation is finished is itself an NSOperation, then you can gracefully handle this by establishing a dependency between them:

[laterOp addDependency:downloadAndParseOp];

The laterOp will be executed only after downloadAndPareOp has finished.

In fact, I would encourage you to write your code so that this approach is possible. One of the biggest strengths of NSOperations and NSOperationQueue is that it easily coordinates code execution.


The usual thing to do is to have the NSOperation call a method on whatever object needs to know that the operation is complete. Or you could use NSNotificationCenter to allow various objects to listen for the update in a more decentralized manner. Or you could use KVO to listen on the NSOperation's isFinished property.


The best way is to initialize your NSOperation with a delegate. When the NSOperation has finished his job, he will call the delegate using one of the delegate's methods (declared through a protocol).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜