NSUInteger奇怪与for循环

时间:2016-09-07 18:55:06

标签: ios objective-c nsuinteger

我使用AppCode来调整我在XCode中编写的代码。 AppCode做了很棒的代码检查,并告诉你哪些方面可以改进。

我遇到的一次频繁检查指出[SomeObjCFrameworkClass objectAtIndex]期待NSUInteger这实际上是真的......

- (ObjectType)objectAtIndex:(NSUInteger)index

然而,我一直在试图遵循这个建议并将我的int更改为NSUInteger来解决自己的问题。

例如,这是我执行此更改时爆炸的一段代码...

-(void)removeBadge
{
    if ([[theButton subviews] count]>0)
    {
        NSUInteger initalValue = [[theButton subviews] count]-1;
        //Get reference to the subview, and if it's a badge, remove it from it's parent (the button)
        for (NSUInteger i=initalValue; i>=0; i--) {

            if ([[[theButton subviews] objectAtIndex:i] isMemberOfClass:[MKNumberBadgeView class]])
            {
                [[[theButton subviews] objectAtIndex:i] removeFromSuperview];
                [theButton setTitleColor:[UIColor lightTextColor] forState:UIControlStateNormal];
            }
        }
    }
}

知道为什么会这样。 下面的调试数据中有一条线索,但我无法理解它。

enter image description here

1 个答案:

答案 0 :(得分:2)

NSUInteger处于无符号状态,因此i>=0循环中的for条件始终评估为YES。在i达到0后,在下一次迭代中,您将获得整数下溢,i变为NSUIntegerMax

更新:据我所知,您的代码没有理由以相反的顺序处理子视图。所以,你可以简单地做到

for (NSUInteger i=0; i<theButton.subviews.count; i++)

否则,您可以使用类似

的内容
if (0 == i) {
    break;
}

在你的循环中或使用do/while例如。