【问题标题】:Why don't NSOperations and sleep work correctly?为什么 NSOperations 和 sleep 不能正常工作?
【发布时间】:2012-06-10 20:54:45
【问题描述】:

在我的应用中,我使用操作来执行耗时的任务,因此我的用户界面不会冻结。为此,我使用 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];
}

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

【问题讨论】:

    标签: objective-c cocoa concurrency nsoperation nsoperationqueue


    【解决方案1】:

    那是因为你在主线程上运行你的操作(同样运行你的用户界面)。

    如果你想同时运行你的操作,创建一个新的操作队列:

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

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2016-07-16
      • 2019-01-04
      • 2020-09-03
      • 2016-10-10
      • 2016-10-24
      • 2017-02-27
      • 2017-07-08
      • 2014-11-23
      相关资源
      最近更新 更多