2013-03-28 46 views
1

声明:在OSX开发中,我是初学者。运行后台任务时的OSX警报

我有一个名为“checkUser”的方法。在该方法中,我需要检查输入的用户凭证是否有效。为了检查凭证是否有效,我需要调用一个名为“methodThatInvolvesNetwork”的方法,其执行时间可能会有所不同,因为它涉及网络连接。在“checkUser”中,我需要显示一个警报,显示“methodThatInvolvesNetwork”正在运行时的进度。用户也可以取消警报,这也将取消正在运行的“methodThatInvolvesNetwork”。 Q1)我应该怎么做?

请注意,“checkUser”的执行被阻止,而“methodThatInvolvesNetwork”在“checkUser”中被调用是必须的。

我目前有此实现:

- (BOOL)checkUser 
{ 
    NSAlert *alert = [NSAlert alertWithMessageText:@"Sample" defaultButton:@"Okay" alternateButton:nil otherButton:nil informativeTextWithFormat:@""]; 
    self.alert = alert; 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
     [self methodThatInvolvesNetwork]; 
    }); 

    [alert runModal]; 
    NSLog(@"After run modal"); 
} 

- (void)methodThatInvolvesNetwork 
{ 
    // Do long running task here. 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     if (self.alert != nil) 
     { 
      [[self.alert window] orderOut:self.alert]; 
      [[NSApplication sharedApplication] stopModal]; 
     } 
    }); 
} 

Q2)是我实现正确的方式去上面呢?
Q3)如果是,那么为什么NSLog(@“After run modal”)在模态警报解除后很久才执行,而不是在模态警告解除后立即执行?

回答

1

要回答我的问题,这是我曾经使用过满足的要求:

  • 与NSWindowController一个NSWindow。
    此窗口将在窗口的加载背景中运行“methodThatInvolvesNetwork”。

  • 内部 “checkUser”,我实例化上面的窗口, “mywindow的”,然后将其传递到:

  • Geowar的回答以上(但没有didEndSelector):

    [NSApp beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:]

  • 上面的行之后,我使用运行它作为模态:

    [NSApp runModalForWindow:myWindow];

    ,以便“checkUser”的执行被阻止。

  • 当“myWindow”结束时(当调用stopModal或abortModal时),则执行“checkUser”将继续。

0

[alert runModal]将不会返回,直到警报解除。如果有一个窗口可以附加到表单中,那么您应该可以使用beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:它将在警报关闭(而不是阻止)时回调选择器。

+0

我需要警报被阻止,以便“checkUser”的返回值基于“methodThatInvolvesNetwork”。 – MiuMiu 2013-03-29 00:48:38