NSOperation with completition block

2019-08-14 15:53发布

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条回答
男人必须洒脱
2楼-- · 2019-08-14 16:15

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.

查看更多
登录 后发表回答