Search code examples
iphoneobjective-cnsarray

Reversing elements in an array in objective-c


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!


Solution

  • 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.