【问题标题】:What's the quickest way to compare a NSUInteger with an int (e.g. 5) in objective-c?在objective-c中将NSUInteger与int(例如5)进行比较的最快方法是什么?
【发布时间】:2011-08-14 09:57:24
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: objective-c xcode xcode4 ocunit


    【解决方案1】:

    使用

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

    (NSUInteger)5 看起来不像5U 那样干净,但它在编译为 64 位时也能正常工作。

    【讨论】:

      【解决方案2】:

      STAssertEquals 要求您将相似类型与相似类型进行比较。因此,将“U”添加到数字以使其成为无符号文字:

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

      或者,您可以使用 OCHamcrest 表示:

      assertThat(nsMutableArrayInstance, hasCountOf(5));
      

      【讨论】:

        【解决方案3】:
        NSUInteger i = 42;
        int j = 5;
        
        if (i > j) {
          NSLog(@"the universe has not ended yet");
        }
        

        您可以使用STAssertTrue,而不是STAssertEquals

        STAssertTrue([nsMutableArrayInstance count] == 5, @"xxxx");
        

        【讨论】:

        • 你也应该能够做到STAssertEquals([nsMutableArrayInstance count], (NSUInteger)5, @"xxxx")
        • STAssertTrue 的问题是当它失败时,它不会说出实际值是多少。
        • 我鼓励按照@JonReid 的建议使用5U
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多