问题描述
Foundation Framework中有三个操作类( NSOperation
, NSInvocationOperation
和 NSBlockOperation
)。
There are three operation classes in Foundation Framework(NSOperation
, NSInvocationOperation
and NSBlockOperation
).
我已经阅读了但我不明白到底是什么这三个类之间的区别。请帮我。
I already read the concurrency programming guide but I did't understand exactly what is the difference between these three classes. Please help me.
推荐答案
表示一个块。 执行(或由target,selector,object定义的方法)。 必须是子类,它提供最大的灵活性但需要最多的代码。
NSBlockOperation
exectues a block. NSInvocationOperation
executes a NSInvocation
(or a method defined by target, selector, object). NSOperation
must be subclassed, it offers the most flexibility but requires the most code.
NSBlockOperation和NSInvocationOperation都是NSOperation的子类。它们由系统提供,因此您无需为简单任务创建新的子类。
NSBlockOperation and NSInvocationOperation are both subclasses of NSOperation. They are provided by the system so you don't have to create a new subclass for simple tasks.
对于大多数任务,使用NSBlockOperation和NSInvocationOperation应该足够了。
Using NSBlockOperation and NSInvocationOperation should be enough for most tasks.
这是一个使用所有三个完全相同的代码示例:
Here is a code example for the use of all three that do exactly the same thing:
// For NSOperation subclass
@interface SayHelloOperation : NSOperation
@end
@implementation SayHelloOperation
- (void)main {
NSLog(@"Hello World");
}
@end
// For NSInvocationOperation
- (void)sayHello {
NSLog(@"Hello World");
}
- (void)startBlocks {
NSBlockOperation *blockOP = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Hello World");
}];
NSInvocationOperation *invocationOP = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(sayHello) object:nil];
SayHelloOperation *operation = [[SayHelloOperation alloc] init];
NSOperationQueue *q = [[NSOperationQueue alloc] init];
[q addOperation:blockOP];
[q addOperation:invocationOP];
[q addOperation:operation];
}
这篇关于NSInvocationOperation和NSBlockOperation之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!