I am currently using GCD. However, I’ve heard that NSOperation is actually a higher level program. It’s far more complex though.
In GCD, do something at background is simply use this helper function I created:
+(void)doForeGround:(void (^)())block
{
dispatch_async(dispatch_get_main_queue(), ^{
block();
});
}
+(void)doBackground:(void (^)())block
{
//DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{
//dispatch_async(dispatch_get_global_queue(-2,0), ^{
block();
});
}
-(void)doBackGround:(void (^)())block onComletion:(void (^)())onCompletion
{
[BGHPTools doBackground:^{
block();
[BGHPTools doForeGround:^{
onCompletion();
}];
}];
}
Will doing it with NSOperation be simpler?
Am I missing something? How would I do the same thing at NSoperation?
You can do similar things with
NSOperationas you’re doing with GCD. The main difference is thatNSOperationprovides additional functionality.For example:
NSOperationhas a-cancelmethod. Dispatch queues have no concept of cancellation; all blocks enqueued on a queue will run to completion.NSOperationQueuehas amaximumConcurrentOperationCountproperty, which you can use (for example) to only allow 3 operations to run at a time. Dispatch queues have no such concept; they are either serial, allowing only 1 block at a time, or concurrent, allowing as many aslibdispatchthinks advisable based on CPU usage and availability.NSOperationcan have a dependency on otherNSOperations, allowing you to defer execution of a particular operation until all of its dependencies have run. Other operations will be allowed to “jump ahead” in the queue while the dependent operation is waiting. Dispatch queues are always dequeued in strictly FIFO order. (You can somewhat imitate dependencies using thedispatch_groupAPI, but that’s really targeted at a different kind of problem.)Now, if you’re not using any of those features, GCD works just fine. There’s nothing wrong with using GCD, per se. It’s just that NSOperation provides a convenient wrapper for some additional nice features.
Here’s how you’d rewrite your examples above using
NSOperationQueue: