NSOperation with completition block

♀尐吖头ヾ 提交于 2019-12-11 08:35:11

问题


I have some image processing that take much time and resources, so i use NSOperation + NSOperatioQueue + delegate for callBack. and all work.

now i want to use blocks because its much elegant and simple to use in a tableView for example.

what i need to do is just like AFJSONRequestOperation for example:

NSURL *url = [NSURL URLWithString:@"url"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
 } failure:nil];
[operation start];

in this example i don't see any operationQueue ! how can i do the same?

    [ImageManagerOperation modifyImage:(UIImage*)image completitionBlock:(void (^)(UIImage *modifiedImage))complete];

where ImageManagerOperation is an NSOperation.

I know that i can set a Completion Block, but i still need to add the operation in a queue.

i want to minimize the line number in my code (if possible :) ).


回答1:


Normally the code in an NSOperation is synchronous. The NSOperationQueue provides the threads needed to run the code in the background. So you add your operation to a queue and the queue then calls start on your operation on a background thread.

AFJSONRequestOperation is a special type of NSOperation called concurrent, this means the operation already provides it's own background threads internally. In some circumstances you may call the start method of a concurrent operation outside of a queue. Because the operation already provides it's own background threads it would still run in the background. In this case start might be called directly just to minimise the code shown in the example.

Normally you would still add concurrent operations to an NSOperationQueue because you want to take advantage of the other things the queue provides such as managing dependancies and the maxConcurrentOperationCount.

So just create yourself an NSOperationQueue and add your operation to it. You wont need to call start the queue will do this for you.



来源:https://stackoverflow.com/questions/15435920/nsoperation-with-completition-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!