为什么 NSOperations 和睡眠不能正常工作?



在我的应用程序中,我使用操作来执行耗时的任务,因此我的用户界面不会冻结。为此,我使用 NSInvocationOperation。我想在实现代码以实际完成任务之前先测试整体架构,所以这就是我现在所拥有的:

// give the object data to process
- (void)processData:(NSObject*)dataToDoTask {
    ... // I store the data in this object
    NSInvocationOperation *newOperation =
    [[NSInvocationOperation alloc] initWithTarget:self
                                         selector:@selector(performTask)
                                           object:nil];
    [[NSOperationQueue mainQueue] addOperation:newOperation];
    ...
}
// process data stored in the object and return result
- (NSObject*)performTask {
    [NSThread sleepForTimeInterval:1]; // to emulate the delay
    return [NSString stringWithFormat:@"unimplemented hash for file %@", self.path];
}

但是,睡眠并没有像我预期的那样工作:它不会延迟操作完成,而是冻结应用程序。似乎我要么操作错误,要么睡眠不正确,但我无法弄清楚哪个以及如何。

这是因为您在主线程上运行操作(与运行用户界面相同)。

如果要同时运行操作,请创建新的操作队列:

NSOperationQueue * queue = [NSOperationQueue new];
[queue addOperation:newOperation];

最新更新