繁体   English   中英

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

[英]Use dispatch_async() inside a method or when calling that method

我正在使用一些下载数据的代码。 代码使用块作为回调。 有几种代码非常相似的下载方法:在回调块中,如果出现问题,它们会显示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()中将调用包装到该方法?

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

方法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,这样你就可以将其他东西添加到队列中。

希望这有帮助!

这与错误或正确无关。

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

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

反之亦然。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM