0

我正在 SpriteKit 中进行测试和原型设计,并有我双击翻转的精灵。我有 52 个精灵_theArray,其中包含当前视图中精灵的名称。当我选择一个精灵时,我希望它位于 zPosition 线程的顶部,通过实现这一点,我使用以下代码刷新所有精灵的 zPosition:

- (void)setTheZposition:(NSString *)nodeNameToCheck {

NSLog(@"++setTheZposition:++");

if (![_node.name isEqual: @"background"]) { // Do not react if background
    [self enumerateChildNodesWithName:nodeNameToCheck usingBlock:^(SKNode *node, BOOL *stop) {

        NSUInteger index = [_theArray indexOfObjectPassingTest:
                            ^(id obj, NSUInteger idx, BOOL *stop) {
                                return [obj hasPrefix:nodeNameToCheck];
                            }];
        NSLog(@"index: %i & length _theArray: %i", index, [_theArray count]);
        [_theArray removeObjectAtIndex:index];
        [_theArray insertObject:nodeNameToCheck atIndex:0];


        // Refresh the zPosition for all sprites
        float positionZ = (int) [_theArray count];
        for (NSString *theNode in _theArray) {
            SKNode *refreshNode = [self childNodeWithName:theNode];
            refreshNode.zPosition = positionZ;
            positionZ--;
        }
    }];
    }
}

只要我只拖动精灵,代码就可以工作,但是当我替换精灵并删除原来的我删除index = 0和添加index = 0_theArray,这似乎是导致问题的原因。

崩溃发生在以下行:

[_theArray removeObjectAtIndex:index];

...索引为:2147483647

...虽然它应该是0

崩溃日志:

2013-09-29 21:08:59.445 testButtonsetc[11597:a0b] ++setTheZposition:++
2013-09-29 21:08:59.446 testButtonsetc[11597:a0b] index: 51 & length _theArray: 52
2013-09-29 21:09:04.112 testButtonsetc[11597:a0b] ++setTheZposition:++
2013-09-29 21:09:04.112 testButtonsetc[11597:a0b] index: 0 & length _theArray: 52
2013-09-29 21:09:04.343 testButtonsetc[11597:a0b] >>>>>>>>T-A-P<<<<<<<<<
2013-09-29 21:09:07.277 testButtonsetc[11597:a0b] ++setTheZposition:++
2013-09-29 21:09:07.278 testButtonsetc[11597:a0b] index: 0 & length _theArray: 52
2013-09-29 21:09:07.477 testButtonsetc[11597:a0b] >>>>>>>>T-A-P<<<<<<<<<
2013-09-29 21:09:10.851 testButtonsetc[11597:a0b] ++setTheZposition:++
2013-09-29 21:09:10.851 testButtonsetc[11597:a0b] index: 2147483647 & length _theArray: 52
2013-09-29 21:09:10.852 testButtonsetc[11597:a0b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM removeObjectAtIndex:]: index 2147483647 beyond bounds [0 .. 51]'

我将非常感谢我能得到的任何帮助。

4

2 回答 2

3

2147483647 是NSNotFound. 您应该NSNotFound在使用indexOfObjectPassingTest:.

来自文档: enum {NSNotFound = NSIntegerMax};

- (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate

返回值 数组中对应值通过谓词指定的测试的最低索引。如果数组中没有对象通过测试,则返回NSNotFound

于 2013-09-29T19:42:34.317 回答
1

- indexOfObjectPassingTest:正在返回NSNotFound,您需要处理这种情况。

于 2013-09-29T19:42:46.810 回答