Hacketo
Hacketo

Reputation: 4997

If statement checking NSArray size

I've an if statement, used to check if an indice is less than the end of the array. This is not working when the value of "i" is -1.

NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:@"coucou"];

int i = -1;

// Not working
if (i < ([myArray count] - 1) ){
    NSLog(@" first ok ");
}

// Fix
int count = [myArray count] - 1;
if ( i < count ){
    NSLog(@" second ok ");
}

This is what i need to do to get it working (same algorithm, but using an intermediate variable to store the size of the array) Anyone know why ?

Upvotes: 0

Views: 729

Answers (3)

KudoCC
KudoCC

Reputation: 6952

[myArray count] return a NSUInteger which is an unsigned integer value.

When you compare an unsigned integer with an signed integer, the signed integer will be convert to unsigned, so the value i is not negative now.

Look here for more information.

Upvotes: 3

Balu
Balu

Reputation: 8460

[myArray count] it returns unsigned long value you need to keep either of these two

((NSInteger)[myArray count] - 1) OR ((int)[myArray count] - 1)

Upvotes: 0

Avinash Tag
Avinash Tag

Reputation: 162

You are comparing a signed integer with int thats why it is happening use NSUInteger instead of int. It will definitely work

Upvotes: 0

Related Questions