0

Is there something I'm missing with NSUInteger. I originally wanted to do this in my .m file. (I saw some code about using an NSEnumerator, but I didn't quite understand it so I thought for my needs, this would be sufficient).

So I wanted to do this:

- (NSArray *)reverseArray:(NSMutableArray *)array {
    NSMutableArray *anArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
    for (NSUInteger i = [array count] - 1; i >= 0 ; i--) {
        [anArray addObject:[array objectAtIndex:i]];
    }
    return anArray;
}

This gives me the compiler warning that i >= 0 is what NSUInteger is designed to do or something along those lines. When I run the program, it also crashes and accesses some super huge number. I'm not quite sure why. I can offset i by 1 everywhere and do this, and this works:

- (NSArray *)reverseArray:(NSMutableArray *)array {
    NSMutableArray *anArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
    for (NSUInteger i = [array count]; (i) ; i--) {
        [anArray addObject:[array objectAtIndex:i - 1]];
    }
    return anArray;
}

I just didn't understand why the first method does not work. Any help would be appreciated. Thanks!

Crystal
  • 28,460
  • 62
  • 219
  • 393

3 Answers3

5

NSUInteger is an unsigned integer. So, if NSUInteger u=0 and if you calculate u-1, it doesn't become -1. Instead, it underflows and it becomes a super huge number.

Changing your code to

 for (NSInteger i = [array count] - 1; i >= 0 ; i--) {

should solve the problem.

Note that you don't really have to reverse the array. The for-loop

for(a in array){
    ... do something with a ...
}

enumerates elements in the forward order, and

for(a in [array reverseObjectEnumerator]){
    ... do something with a ...
}

enumerates elements in the reverse order.

Yuji
  • 34,103
  • 3
  • 70
  • 88
1

An unsigned integer is always >= 0. So your first loop will never terminate, which eventually results in it trying to access the objectAtIndex:(NSUInteger)-1, which is actually a very large positive index, causing the crash.

Fortunately, you seem to have figured out how to fix the problem already. Good work.

Note that there is nothing specific to Objective-C about this; programmers commonly make the same mistake with unsigned integers in basically every suitably low-level language.

Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
0

NSUInteger is "unsigned", meaning it can't have the - sign denoting a negative number. In your code...

NSUInteger i = [array count] - 1; i >= 0 ; i--

That will eventually equal -1, hence the error. Try removing = for something like this.

NSUInteger i = [array count] - 1; i > 0 ; i--
damon
  • 1,087
  • 9
  • 12