在方法内部或调用该方法时使用dispatch_async()

时间:2013-05-08 20:13:17

标签: ios objective-c block grand-central-dispatch

我正在使用一些下载数据的代码。代码使用块作为回调。有几种下载方法具有非常相似的代码:在回调块中,如果出现问题,它们会显示UIAlertView。警报视图始终如下所示:

[req performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
    if(error) {
        dispatch_async(dispatch_get_main_queue(), ^{

            [[NSNotificationCenter defaultCenter] postNotificationName:kFailed object:nil];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                         message:@"Connection failed"
                                                        delegate:nil
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
            [alertView show];
        });
    }
}];

我想将警报视图代码移动到它自己的方法,因为它使用相同的参数多次调用。我是否应该将dispatch_async()移动到方法中,还是应该在dispatch_async()中将调用包装到该方法?

2 个答案:

答案 0 :(得分:0)

你可以这样做。从功能上讲,这两个代码块是相同的:

方法1

//.... Assuming this is called in a block
dispatch_async(dispatch_get_main_queue(), ^{
    [self showMyAlertView];
});

- (void) showMyAlertView {
    // Show the alert view and other stuff
}

方法2

//.... Assuming this is also called in your block
[self showMyAlertView];

- (void) showMyAlertView {
    dispatch_async(dispatch_get_main_queue(), ^{
        // Show the alert view and other stuff
    });
}

显然,第二种方式需要最少的代码行,但是如果你想异步地做其他事情(除了显示你的警报视图),你可能想要做方法1,这样你就可以将其他东西添加到队列中。

希望这有帮助!

答案 1 :(得分:0)

这与错误或正确无关。

优点:如果将dispatch_async()放在方法中,则可以从程序的每个位置发送消息,而不管您运行的是什么线程。

缺点:如果将dispatch_async()放在方法中,即使从主线程发送消息,代码也始终执行异步。 (在这种情况下,dispatch_async()根本不是必需的,dispatch_sync()将死锁。)

反之亦然。

对我来说,不同的东西更重要:定义一层“调度方法”。仅在此图层中使用dispatch_async()和dispatch_sync(),而不是在此之上构建的图层中,而不是在此图层下构建的图层中。

从较高级别的软件中始终使用此图层。在图层内部仅使用较低图层上的方法。