2013-03-12 73 views
2
-(NSInteger) buttonIndexWithMessage:(NSString *) title andArrayOfOptions:(NSArray *) options 
{ 
    self.operation=[NSOperationQueue new]; 

    [self.operation addOperationWithBlock:^{ 
     [[NSOperationQueue mainQueue]addOperationWithBlock:^{ 
      UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title 
                    delegate:self 
                  cancelButtonTitle:nil 
                 destructiveButtonTitle:nil 
                  otherButtonTitles:nil]; 

      for (NSString * strOption in options) { 
       [actionSheet addButtonWithTitle:strOption]; 
      } 

      [actionSheet showInView:[BGMDApplicationsPointers window]]; 
     }]; 
     self.operation.suspended=true; //Okay make t 
    }]; 

    [self.operation waitUntilAllOperationsAreFinished];//Don't get out of the function till user act. 

    //Wait till delegate is called. 
    return self.buttonIndex;//I want to return buttonIndex here. 
} 

執行點不斷移動,直到返回self.buttonIndex,即使self.operation尚未完成。爲什麼waitUntilAllOperationsAreFinished不會在此代碼中等待?

回答

1

你怎麼知道self.operation尚未完成?添加到其中的操作執行起來非常快:它只是將另一個操作添加到主隊列中。

你似乎認爲行

self.operation.suspended=true; 

應該阻止正在進行的操作。但是從documentation

此方法暫停或恢復執行操作。 掛起一個隊列會阻止該隊列啓動其他的 操作。換句話說,隊列中的操作(或稍後添加到隊列中的 )且尚未執行的操作將從 開始,直到隊列恢復爲止。暫停隊列不會停止已經運行的操作 。

您的操作已在運行,因此不受影響。

你爲什麼不告訴我們你實際想要達到的目標,並且我們可以建議如何實現這個目標的好方法。

+0

我想用函數樣式來轉換委託樣式調用。所以我想創建一個顯示UIActionSheet並返回索引用戶選擇的函數。 – 2013-03-12 14:16:28

+0

如何暫停一個線程呢? – 2013-03-12 14:17:04

+0

你在找什麼是線程同步。您的後臺線程需要阻塞,直到在主線程上檢測到按鈕按下爲止。請參閱https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html。 – fishinear 2013-03-12 14:32:12

0

第一個問題是,你每次暫停添加的操作在這裏:

self.operation.suspended=true; 

所以他們不會執行。

另一個問題是,不能保證塊將立即執行,因爲你只是將它添加到主操作隊列中。一旦將其添加到主操作隊列中,您就不知道它將在何時安排。我會改變這種方式的代碼:

[self.operation addOperationWithBlock:^{ 
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title 
                   delegate:self 
                 cancelButtonTitle:nil 
                destructiveButtonTitle:nil 
                 otherButtonTitles:nil]; 
    for (NSString * strOption in options) { 
     [actionSheet addButtonWithTitle:strOption]; 
    } 
    [actionSheet showInView:[BGMDApplicationsPointers window]]; 
}]; 
0

操作已完成!您正在等待快速完成的操作:所有操作都會將操作添加到mainQueue。 mainQueue中發生的事情可能需要一段時間才能完成,但這不是您正在等待的操作。

相關問題