NSArraym在被枚举时被突变,sqlite3在循环时被突变?

时间:2014-11-11 06:44:33

标签: while-loop nsmutablearray sprite-kit dispatch-async

我收到错误:NSArrayM在枚举时发生了变异,我已经尝试了几乎所有我能在stackoverflow上找到的东西。请记住,我在创建游戏时学习:)

我使用精灵套件并在didmovetoview中使用dispatch_async来加载游戏。

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
       // loading stuff, but also this that is causing the error:
       [self buildmap];
    dispatch_async(dispatch_get_main_queue(), ^(void){
        // done loading
    });
});

这是导致崩溃的构建图。

-(void)buildMap {

    int intX = 0;
    int intY = 0;

    sqlite3_stmt *statement;
    if (sqlite3_open([_databasePath UTF8String], &BlockMinerDB) == SQLITE_OK) {

        NSString *sql = [NSString stringWithFormat:@"SELECT blocktype, ladder, blockreachable, walkable, zpos, texture, id, bitmask FROM map ORDER BY id DESC"];
        const char *qstmt = [sql UTF8String];

        if (sqlite3_prepare_v2(BlockMinerDB, qstmt, -1, &statement, NULL) == SQLITE_OK) {

            while (sqlite3_step(statement) == SQLITE_ROW) {

                int blockType = sqlite3_column_int(statement, 0);
                int ladder = sqlite3_column_int(statement, 1);
                int blockReachable = sqlite3_column_int(statement, 2);
                int walkable = sqlite3_column_int(statement, 3);
                int zPos = sqlite3_column_int(statement, 4);
                NSString *texture = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 5)];
                int idBlock = sqlite3_column_int(statement, 6);
                uint32_t newBitmask = (uint32_t)[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 7)];



                Blocks *testblock = [[Blocks alloc] initWithBlock:blockType blockId:idBlock ladder:ladder scene:self bitmask:newBitmask blockReachable:blockReachable walkable:walkable zPos:zPos texture:texture x:intX y:intY];

                NSLog(@"%@: %i", testblock.name, blockType);

                if ((blockType == 2) || (blockType == 3) || (blockType == 4) || (blockType == 5)) {
                    [blockArrayWalk addObject:testblock];
                } else {
                    [blockArray addObject:testblock];
                }


                [background addChild:testblock];
                intX++;
                if (intX == 25) {
                    intX = 0;
                    intY++;
                }
            }
        }
    }
    sqlite3_close(BlockMinerDB);
}

[self buildmap]使用sqlite从数据库中检索地图,我使用while循环进行循环,这导致崩溃。它会在崩溃之前循环约20-25次(600次)。

在循环中我创建了一个新块(SKSpriteNode子类),它将块放置在某个位置,包含一些信息(位置,名称,物理等,没有重物)。我使用NSMutableArray来存储块以便于访问,并且认为这首先是问题,但是当我删除[blockArray addObject:block]时;该应用程序仍然崩溃。

如果删除 - (void)构建图中的每一段代码,应用程序都不会崩溃。

是否存在dispatch_async以及可能导致此问题的while循环?

我现在无法访问代码,但如果有人需要查看更多代码,我可以在大约8小时后添加此代码;)非常感谢一些帮助,尝试解决此错误3周现在:D

1 个答案:

答案 0 :(得分:1)

在任何时候,Sprite Kit可能会枚举孩子(也许是为了绘制它们),如果你的调度块然后添加一个新的子节点,它会导致子数组在枚举时发生变异。

您可以在调度块中填充一系列待添加节点,然后在调度块之后立即添加它们。