2012-06-10 23 views
1

在我的應用程序中,我使用操作執行耗時的任務,因此我的用戶界面不會凍結。爲此,我使用NSInvocationOperation。我想執行的代碼,但要完成的任務之前,先測試整體架構,所以這就是我現在所擁有的:爲什麼NSOperations和睡眠不能正常工作?

// 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]; 
} 

然而,正如我所期望的睡眠不工作:不是延遲操作完成,它凍結了應用程序。看來我無論是手術還是睡眠不正確,但我無法弄清楚是哪一種以及如何。

回答

3

這是因爲您正在主線程上運行您的操作(同樣運行您的用戶界面)。

如果你想同時運行操作,創建一個新的操作隊列:

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