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!

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.