我正在SpriteKit中进行测试和原型制作,并且有双击双击即可翻转的精灵。我在_theArray中有52个精灵,其中包含当前视图上的精灵的名称。当我选择一个精灵时,我希望它位于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]'


我将非常感谢我能提供的任何帮助。

最佳答案

2147483647是NSNotFound。使用NSNotFound时应测试indexOfObjectPassingTest:

从文档中查找:
enum {NSNotFound = NSIntegerMax};

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

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

10-08 16:58