【问题标题】:Custom block inside dispatch_asyncdispatch_async 中的自定义块
【发布时间】:2012-09-27 13:26:58
【问题描述】:

此代码有效

[[MyManager sharedManager] makeRequestAndParsingfor:someParameters 
                                            success:^(NSDictionary * dictionary){
                                                // Sucessful response
                                                NSLog(@"Success!!");
                                            } 
                                            failure:^(NSError* error){ 
                                                // Error response
                                                NSLog(@"Failure!");    
                                            }];

但是每当我在后台运行它时,它永远不会进入成功或失败块。

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    [[MyManager sharedManager] makeRequestAndParsingfor:someParameters 
                                                success:^(NSDictionary * dictionary){
                                                    // Sucessful response
                                                    NSLog(@"Success!!");
                                                } 
                                                failure:^(NSError* error){ 
                                                    // Error response
                                                    NSLog(@"Failure!");    
                                                }];
}];

谁能解释一下发生了什么? ma​​keRequestAndParsingfor 方法:发出异步请求(再次使用块),然后解析结果。我的调试器显示在第二种情况下它永远不会获得自己的成功/失败。在第一种情况下,它就像一个魅力。有什么想法吗?

【问题讨论】:

    标签: iphone ios cocoa-touch cocoa


    【解决方案1】:

    您的方法“makeRequestAndParsingfor”是否使用 args 的 block_copy(),并将返回值存储在一个强变量中(以获取堆中的块)?还要添加asserts(),这样你就可以验证你在'makeRequestAndParsingfor'中得到了两个块,甚至在调用一个或另一个之前重新测试。 [过去使用 block_copy() 是必要的,但现在不是 100% 确定。]

    请注意,在第二种情况下,“makeRequestAndParsingfor”在并发队列中运行,其中多个可以同时调用块 - 不确定您的成功/失败块的作用,但最好是线程安全的,或者您应该运行'makeRequestAndParsingfor' 中主队列上的块(我在类似构造的应用程序中这样做)。

    【讨论】:

    • 不,我不使用 block_copy()。如果我在主队列中运行相同的程序,它就可以工作。但我不想阻塞主线程。是否可以?你能开个聊天室吗?
    • 我的理解是,Apple(曾经)在 SDK 中向我们公开的每个方法中都使用了 block_copy() 来获取传入的块参数,但我不确定你是否可以现在将它们分配给一个强变量以“保留”它们(可能你可以)。但是,当然,打开一个聊天室。
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2021-11-04
    • 2019-05-19
    相关资源
    最近更新 更多