数组索引中的逻辑问题

时间:2013-12-16 18:33:30

标签: ios nsarray

我可能已经开始这么长时间,根本无法看到逻辑问题。我正在改变平移手势上的背景图像。向左/向右滑动可以循环显示背景和循环的图像名称数组。

向右滑动(增加)工作正常,它循环回到我的数组的开头。 向左滑动(减少数组中第一个对象的停止(objectIndex:0)。

NSLog(@"_imageBackgroundIndex Before:%d",_imageBackgroundIndex);

if ([_panDirection isEqual:@"Right"]) 
{ 
    _imageBackgroundIndex = _imageBackgroundIndex + 1;
}

if ([_panDirection isEqual:@"Left"]) 
{ 
    _imageBackgroundIndex = _imageBackgroundIndex - 1;
}


NSLog(@"_imageBackgroundIndex After:%d",_imageBackgroundIndex);

if (_imageBackgroundIndex > ([_backgroundImages count] - 1)) 
{ 
    _imageBackgroundIndex = 0;
}

if (_imageBackgroundIndex < 0) 
{ 
    _imageBackgroundIndex = ([_backgroundImages count] - 1);
}


[[self childNodeWithName:kBackgroundName] runAction:
    [SKAction setTexture:
        [SKTexture textureWithImageNamed:
            [_backgroundImages objectAtIndex:_imageBackgroundIndex]]]];

有人看到了这个问题吗?

1 个答案:

答案 0 :(得分:0)

代码看起来没问题(尽管有一些样式改进,一旦你开始工作就要考虑)。我打赌您已将_imageBackgroundIndex声明为unsigned intNSUInteger。当你认为它低于零时,它实际上是一个巨大的无符号值。

即使计数器声明为无符号,此代码也可以工作(并且具有更好的样式)

- (void)incrementIndex {
    BOOL increment = self.imageBackgroundIndex < self.backgroundImages.count-1;
    self.imageBackgroundIndex = (increment)? self.imageBackgroundIndex+1 : 0;
}

- (void)decrementIndex {
    BOOL decrement = self.imageBackgroundIndex > 0;
    self.imageBackgroundIndex = (decrement)? self.imageBackgroundIndex-1 : self.backgroundImages.count-1;
}

然后你的pan方法变得更简单:

// not sure how panDirection is initialized, is it really a string @"Left" or @"Right"?
// if so, use isEqualToString to compare strings

if ([_panDirection isEqualToString:@"Right"]) [self incrementIndex];
else if ([_panDirection isEqualToString:@"Left"]) [self decrementIndex];

[[self childNodeWithName:kBackgroundName] runAction:// ... etc