在Objective-c中比较NSUInteger和int(例如5)的最快方法是什么?

Gre*_*reg 21 xcode objective-c ocunit xcode4

在Objective-c中比较NSUInteger和int(例如5)的最快方法是什么?

背景 - 我注意到以下代码行给出了错误:

STAssertEquals([nsMutableArrayInstance count], 5, @"xxxx");
// gives Type Mismatch
Run Code Online (Sandbox Code Playgroud)

所以我有效地问的是如何纠正这个以修复错误...

Jon*_*eid 50

STAssertEquals要求您将类似类型与类似类型进行比较.因此,在数字上添加"U",使其成为无符号文字:

STAssertEquals([nsMutableArrayInstance count], 5U, nil);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用OCHamcrest来说:

assertThat(nsMutableArrayInstance, hasCountOf(5));
Run Code Online (Sandbox Code Playgroud)


Dav*_*ong 7

NSUInteger i = 42;
int j = 5;

if (i > j) {
  NSLog(@"the universe has not ended yet");
}
Run Code Online (Sandbox Code Playgroud)

而不是使用STAssertEquals,你可以使用STAssertTrue:

STAssertTrue([nsMutableArrayInstance count] == 5, @"xxxx");
Run Code Online (Sandbox Code Playgroud)

  • "STAssertTrue"的问题在于,当它失败时,它不会说实际值是什么. (6认同)
  • 我鼓励使用`5U`作为@JonReid建议. (5认同)