Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: Unsigned int compare

So I ran into a huge issue at work because I had something like this in my code:

    int foo = -1;
    NSArray *bar = [[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil];
    if (foo > [bar count]){
        NSLog(@"Wow, that's messed up.");
    } else {
        NSLog(@"Rock on!");
    }

As you probably already know by me posting this, the output is:

"Wow, that's messed up."

From what I gather, objective C is converting my negative number to a "signed" int and thus, killing my compare.

I saw other posts about this and they all stated what the problem was but none of them suggested any simple solutions to get this comparison to actually work. Also, I'm shocked that there are no compiler warnings, as these are causing serious issues for me.

like image 388
William T. Avatar asked Apr 23 '13 04:04

William T.


1 Answers

The problem

The problem you're experiencing is that because foo is a signed integer and -[NSArray count] returns an unsigned integer, foo is undergoing implicit type conversion to unsigned integer. See Implicit Type Conversion for more information. Also, there's more information about type conversion rules in C here.

The solution

-[NSArray count] returns an unsigned value because an array can never have a negative number of elements; the smallest possible value is 0. Comparing an array's count to -1 doesn't make a lot of sense -- the count will always be larger than any negative number (sign problems notwithstanding).

So, the right solution here, and the way to avoid these kinds of problems, is to use a type that matches the return value of -[NSArray count], namely NSUInteger (the U is for unsigned).

like image 196
Caleb Avatar answered Oct 06 '22 07:10

Caleb