Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the quickest way to compare a NSUInteger with an int (e.g. 5) in objective-c?

Tags:

What's the quickest way to compare a NSUInteger with an int (e.g. 5) in objective-c?

Background - I'm noting that the following line of code gives an error:

STAssertEquals([nsMutableArrayInstance count], 5, @"xxxx");
// gives Type Mismatch

So what I'm asking effectively is how to correct this to fix the error...

like image 240
Greg Avatar asked Apr 28 '11 05:04

Greg


3 Answers

STAssertEquals requires that you compare like types to like types. So add "U" to the number to make it an unsigned literal:

STAssertEquals([nsMutableArrayInstance count], 5U, nil);

Alternatively, you could use OCHamcrest to say:

assertThat(nsMutableArrayInstance, hasCountOf(5));
like image 190
Jon Reid Avatar answered Oct 05 '22 11:10

Jon Reid


NSUInteger i = 42;
int j = 5;

if (i > j) {
  NSLog(@"the universe has not ended yet");
}

Instead of using STAssertEquals, you could use STAssertTrue:

STAssertTrue([nsMutableArrayInstance count] == 5, @"xxxx");
like image 39
Dave DeLong Avatar answered Oct 05 '22 13:10

Dave DeLong


Use

STAssertEquals([nsMutableArrayInstance count], (NSUInteger)5, @"xxxx");

(NSUInteger)5 does not look as clean as 5U but it will also work correctly when compiling for 64-bit.

like image 27
murat Avatar answered Oct 05 '22 12:10

murat