2013-03-12 74 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中发生的事情可能需要一段时间才能完成,但这不是您正在等待的操作。

相关问题