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

3

21

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

Eimile answered 28/4, 2011 at 5:26 Comment(0)
E
7
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");
Esposito answered 28/4, 2011 at 5:27 Comment(3)
You should also just be able to do STAssertEquals([nsMutableArrayInstance count], (NSUInteger)5, @"xxxx").Meyerhof
The problem with the STAssertTrue is that when it fails, it won't say what the actual value was.Arundel
I encourage using 5U as @JonReid suggests.Anette
A
50

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));
Arundel answered 2/5, 2011 at 20:56 Comment(0)
E
7
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");
Esposito answered 28/4, 2011 at 5:27 Comment(3)
You should also just be able to do STAssertEquals([nsMutableArrayInstance count], (NSUInteger)5, @"xxxx").Meyerhof
The problem with the STAssertTrue is that when it fails, it won't say what the actual value was.Arundel
I encourage using 5U as @JonReid suggests.Anette
S
3

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.

Samathasamau answered 11/9, 2013 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.