ios - 是否可以避免编写此 block 调用代码 'backwards' ?

标签 ios objective-c objective-c-blocks grand-central-dispatch

我在 Objective C 中有一个异步方法,您将完成处理程序传递给该方法。

我希望在两个不同的对象上有条件地运行此方法两次,然后处理结果。

我能找到使这项工作成功的唯一方法是按照以下“向后”编写代码。

这意味着我在架构方面存在重大失败。有没有更好的办法?

定义.h

    #define BLOCK_SAFE_RUN(block, ...) block ? block(__VA_ARGS__) : nil

myController.h

    // Code executes in the order (0),(1),(2),(3),(4) - see comments


    // (0) Create the origin completion handler
    void (^originCompletionHandler)(FAPlacePoint *, BOOL, BOOL) = ^void (FAPlacePoint *savedOriginPP, BOOL geoCodeDidSucceed, BOOL saveDidSucceed)
    {

        // (2) Create the destination completion handler
        void (^destinationCompletionHandler)(FAPlacePoint *, BOOL, BOOL) = ^void (FAPlacePoint *savedDestinationPP, BOOL geoCodeDidSucceed, BOOL saveDidSucceed)
        {

            // (4)
            // Everything is finished.  Do something with savedOriginPP and savedDestinationPP


        };

        // (3) Conditionally run the geocode method with the dest point then call the destination completion handler
        if (destinationPlacePoint.currentLocation)
            [self reverseGeocodeThenSavePlacePoint:destinationPlacePoint completion:destinationCompletionHandler];
        else
        {
            FAPlacePoint * pp = [self storePlacePoint:destinationPlacePoint];
            BLOCK_SAFE_RUN(destinationCompletionHandler, pp, YES, YES);
        }


    };


    // (1) Conditionally run the geocode method with the origin point then call the origin completion handler
    if (originPlacePoint.currentLocation)
        [self reverseGeocodeThenSavePlacePoint:originPlacePoint completion:originCompletionHandler];
    else
    {
        FAPlacePoint * pp = [self storePlacePoint:originPlacePoint];
        BLOCK_SAFE_RUN(originCompletionHandler, pp, YES, YES);
    }

最佳答案

This implies a major architectural failing on my part. Is there a better way?

不,它没有。也许你只需要调整一下你的观点。

在定义变量之前,您不能使用变量来调用 block ,因此完成处理程序之类的代码将始终位于调用它的代码之前。这没有错。这就像在执行计划之前告诉某人您的计划:离开办公室后,我会在杂货店停下来。计算机语言通常没有实际的将来时,但考虑一下可能会有所帮助在调用 block 之前定义 block ,就像用将来时写代码一样。

如果在导致它运行的代码之前有完成代码真的让您感到困扰,您有时可以将该代码放在它自己的方法中,这样完成 block 本身就只包含很少的内容而不是对该方法的调用。当然,该方法可以跟随调用它的代码(但完成 block 本身仍然需要在您使用它之前定义)。

关于ios - 是否可以避免编写此 block 调用代码 'backwards' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303231/

相关文章:

linux - Linux 上源代码构建的 clang-3.7 找不到 Block_copy

objective-c - 除了弱/强舞蹈之外,还有什么方法可以在 block 中使用实例变量吗?

ios - 如何手动设置 titleForHeaderInSection

ios - 如何在对象 C 或 Swift 中获取设备序列号

ios - 在 UITableView 中自动更新背景

ios - 按下按钮时 UIViewcontroller 不打开

ios - 可以从共享点 url 运行 WKWebView 吗?

ios - IBAction 方法中调用的完成处理程序

ios - 使用自定义单元格类时出现 Tableview 错误

ios - 如何从ios设备中的URL存储json数据并在本地使用它