NSOperation与补全块 [英] NSOperation with completition block
问题描述
我有一些图像处理需要很多时间和资源,因此我使用 NSOperatioQueue
+回调的委托.和所有的工作.
I have some image processing that take much time and resources, so i use NSOperation
+ NSOperatioQueue
+ delegate for callBack. and all work.
现在我要使用块,因为例如在tableView中使用它非常优雅和简单.
now i want to use blocks because its much elegant and simple to use in a tableView for example.
我需要做的就像 AFJSONRequestOperation
一样:
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];
在此示例中,我看不到任何operationQueue!我该怎么办?
in this example i don't see any operationQueue ! how can i do the same?
[ImageManagerOperation modifyImage:(UIImage*)image completitionBlock:(void (^)(UIImage *modifiedImage))complete];
其中ImageManagerOperation是NSOperation.
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 :) ).
推荐答案
通常,NSOperation
中的代码是同步的. NSOperationQueue
提供在后台运行代码所需的线程.因此,您将操作添加到队列中,然后队列在后台线程上的操作上调用start
.
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
是称为concurrent
的NSOperation
的特殊类型,这意味着该操作已经在内部提供了自己的后台线程.在某些情况下,您可以在队列外部调用concurrent
操作的start
方法.因为该操作已经提供了它自己的后台线程,所以它仍将在后台运行.在这种情况下,可以直接调用start
只是为了最小化示例中显示的代码.
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.
通常,您仍然会向NSOperationQueue
添加concurrent
操作,因为您想利用队列提供的其他功能,例如管理dependancies
和maxConcurrentOperationCount
.
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
.
因此,只需为自己创建一个NSOperationQueue
并将其添加操作即可.您无需呼叫start
队列将为您完成此操作.
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.
这篇关于NSOperation与补全块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!