cocos2d无法异步添加子进程

时间:2012-08-03 14:42:56

标签: ios asynchronous cocos2d-iphone cclayer

我需要从数据库中检索一些数据以显示在屏幕上。我想避免应用程序阻塞,所以我在检索任何数据之前显示下一个屏幕,并在数据进入时添加数据。

这是在屏幕上添加我需要的信息的方法:

- (void)initInfo
{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    CCMenu *infoMenu;

    // get the info in seperate thread since it may block
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        infoMenu = [PlayerInfoHelper generateInfoForPlayerWithId:[PlayerManager sharedInstance].activePlayer.objectId tag:-1 sender:self];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (infoMenu != nil) {
                infoMenu.position = ccp(winSize.width - kSSInfoPaddingX, winSize.height - kSSInfoPaddingY);
                [self addChild:infoMenu z:zIndex++]; // (1)
            }
        });
    });
}

方法generateInfoForPlayerWithId:tag:sender:可能阻塞,这就是我把它放在自己的线程中的原因。我在主线程中添加了菜单,因为它是一个UI更新。

我确信infoMenu是一个正确的CCMenu *对象。

当我没有注释掉用//(1)表示的行时,我得到一个EXC_BAD_ACCESS。

1 个答案:

答案 0 :(得分:2)

要在后台线程中运行Cocos2D,您需要创建一个新的EAGLContext。像这样:

- (void)createMySceneInBackground
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    EAGLContext *k_context = [[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:[[[[CCDirector sharedDirector] openGLView] context] sharegroup]] autorelease];
    [EAGLContext setCurrentContext:k_context];

    if (infoMenu != nil) {
        infoMenu.position = ccp(winSize.width - kSSInfoPaddingX, winSize.height - kSSInfoPaddingY);
        [self addChild:infoMenu z:zIndex++]; // (1)
    }

    [pool release];
}
祝你好运!