cocoa :调度设计模式

标签 cocoa dispatch

-(void) test{
    for(Person *person in persons){
        __block CGPoint point;
        dispatch_async(dispatch_get_main_queue(), ^{
            point = [self.myview personToPoint:person];
        });
        usePoint(point); // take a long time to run
    }
}

我需要在主队列中运行 personToPoint() 来获取点,而 usePoint() 方法不需要在主队列中运行并采取运行时间很长。然而,当运行usePoint(point)时,由于使用了dispatch_async,point还没有被赋值。如果使用dispatch_sync方法,程序会被阻塞。分配后如何使用点?

更新: 如何实现以下代码的模式:

-(void) test{
    NSMutableArray *points = [NSMutableArray array];
    for(Person *person in persons){
        __block CGPoint point;
        dispatch_async(dispatch_get_main_queue(), ^{
            point = [self.myview personToPoint:person];
            [points addObject:point];
        });
    }
    usePoint(points); // take a long time to run
}

最佳答案

像下面这样的东西就可以了。您还可以将整个 for 循环放在一个dispatch_async() 中,并让主线程一次调度所有 usePoint() 函数。

-(void) test{
    for(Person *person in persons){
        dispatch_async(dispatch_get_main_queue(), ^{
            CGPoint point = [self.myview personToPoint:person];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                usePoint(point); // take a long time to run
            });
        });
    }
}

更新问题的解决方案:

您使用与上面建议的相同的基本模式。也就是说,您将主线程上需要执行的操作分派(dispatch)到主线程,然后将分派(dispatch)嵌套回主线程分派(dispatch)内的默认工作队列。因此,当主线程完成其工作时,它将把耗时的部分分派(dispatch)到其他地方完成。

-(void) test{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSMutableArray *points = [NSMutableArray array];
        for (Person *person in persons){
            CGPoint point = [self.myview personToPoint:person];
            [points addObject:[NSValue valueWithCGPoint:point]];
        }
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            usePoint(points); // take a long time to run
        });    
    });
}

请注意,您的代码中存在错误,因为您无法将 CGPoint 添加到 NSArray,因为它们不是对象。您必须将它们包装在 NSValue 中,然后在 usePoint() 中解开它们。我使用了仅适用于 iOS 的 NSValue 扩展。在 Mac OS X 上,您需要将其替换为 [NSValue valueWithPoint:NSPointToCGPoint(point)]

关于 cocoa :调度设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12032313/

相关文章:

macos - 如何在 Swift 中设置 NSButton 的 keyEquivalent 为 NSDownArrowFunctionKey

python - Google 应用程序引擎模块 :Confused about routing (dispatch. yaml)

javascript - 错误类型错误 : Cannot convert undefined or null to object

cocoa - 意想不到的优秀背景CATransaction

objective-c - 同时采用 NSArray 和 NSMutableArray 的方法

r - 关于 UseMethod 搜索机制的困惑

ios - 无法弄清楚如何管理 MBProgressHUD 和调度

ios - 清除方法中的静态变量

objective-c - 指针与整数的比较

iOS : Fail to use Global object class - Singleton