objective-c - main() 未在非并发 NSOperation 中调用

标签 objective-c nsoperation nsoperationqueue

当创建一个 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/

相关文章:

ios - 带有 iOS 7 的 UIAlertController (UIAlertControllerStyleActionSheet)

objective-c - 将一个项目分成多个Xcode项目文件

iphone - 在 iOS 中关闭 UIPickerView

ios - 在 iOS 中旋转 View 时如何计算仿射平移参数?

iphone - NSBlockOperation 在 NSOperation 中调用一个方法

ios - NSOperation with NSTimer循环如何停止它

ios - 带有 NSOperation 的 MagicalRecord 导致持久性问题

ios - NSOperation。取消与完成状态

swift - NSOperationQueues 在被释放之前总是完成它们的队列吗?

ios - 调用 [operation cancelAllOperations] 时 NSOperationQueue 不会停止