Objective c 为什么WaitUntlallOperations完成不';我不能在这代码中等待吗?

Objective c 为什么WaitUntlallOperations完成不';我不能在这代码中等待吗?,objective-c,xcode,Objective C,Xcode,即使self.operation尚未完成,执行点仍会一直移动,直到返回self.buttonIndex。第一个问题是您在此处暂停了所有添加的操作: -(NSInteger) buttonIndexWithMessage:(NSString *) title andArrayOfOptions:(NSArray *) options { self.operation=[NSOperationQueue new]; [self.operation addOperationWithB

即使self.operation尚未完成,执行点仍会一直移动,直到返回self.buttonIndex。

第一个问题是您在此处暂停了所有添加的操作:

-(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.operation.suspended=true; 

你怎么知道self.operation还没有完成?您添加到其中的操作执行起来非常快:它只是将另一个操作添加到主队列中

你似乎认为这条线

[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]];
}];
应该阻止正在进行的操作。但从以下方面:

此方法暂停或恢复操作的执行。 挂起队列可防止该队列启动其他队列 操作。换句话说,队列中的操作(或添加的操作) (稍后发送到队列)和尚未执行的 开始,直到队列恢复。挂起队列不会停止 已在运行的操作

您的操作已在运行,因此不受影响


你为什么不告诉我们你真正想要实现的目标,我们可以建议一些好的方法来实现这一目标。

操作已经完成!您正在等待一个快速完成的操作:该操作所做的只是将一个操作添加到mainQueue。主队列中发生的事情可能需要时间才能完成,但这不是您正在等待的操作。

我想将委托式调用与函数式调用结合起来。所以我想创建一个函数,它将显示UIActionSheet并返回用户选择的索引。在主线程上检测到按钮按下之前,背景线程需要阻塞。但是,您确实意识到整个UI是异步的。如果您真的坚持使用同步的“函数式”UI交互,那么您需要在后台线程中运行整个程序,这将导致大量问题。
self.operation.suspended=true;