当创建一个 NSOperation 并将其放入 NSOperationQueue 时,我从未看到 main() 被调用。只有 start() 被调用。我没有做任何花哨的事情,真的。作为一个简单的测试,我写了这个:
NSOperationQueue *testOperationQueue = [[NSOperationQueue alloc] init];
MyTestOperation *testOperation = [[MyTestOperation alloc] init];
[testOperationQueue addOperation:testOperation];
在 MyTestOperation.m 中:
- (void)main
{
NSLog(@"testing if main is getting called");
}
- (void)start
{
NSLog(@"testing if start is getting called");
}
MyTestOperation.h 看起来像这样:
#import <Foundation/Foundation.h>
@interface MyTestOperation : NSOperation
@end
我是否遗漏了一些明显的东西?
[编辑注:我其实是说non-concurrent,不是concurrent(上一个标题写的)。]
最佳答案
我研究了您的代码并注意到如果我完全注释掉您的 start
方法,main
方法将会运行。在更仔细地阅读了 start
的文档之后,我发现了这一行:
The default implementation of this method updates the execution state of the operation and calls the receiver’s
main
method.
因此,通过使用未调用 main
的实现覆盖 start
,您有效地缩短了操作,并且从未允许它真正开始工作!因此,您要么需要在 start
方法中显式调用 main
,要么您需要一起消除 start
,如果您实际上不是用它来设置/更新执行状态/等。
关于objective-c - main() 未在非并发 NSOperation 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14658609/