0

I am writing a unit test for an object that has an NSUInteger property and I'm getting a type mismatch when I compare to 0. Can someone explain why?

My object definition:

@interface Item : NSObject

@property (nonatomic) NSUInteger n;

// stuff deleted...
@end

And the line from my unit test that gets a type mismatch error:

STAssertEquals(0, i.n, @"n property should be zero");

I also tried 0L and I get a type mismatch with that as well. I have worked around this by declaring an NSUInteger variable called "zero" and setting that to 0, then using that for the compare, but I'd like to better understand what's going on here.

Thanks!

4

3 回答 3

3

The reason for this is that the macro STAssertEquals uses strcmp(@encode(__typeof__(a1)), @encode(__typeof__(a2)) to decide if the two parameters have the same type. If not, the macro raises an exception with the message "Type mismatch -- "...

So you cannot use STAssertEquals on compatible types, they have to match exactly:

STAssertEquals((NSUInteger)0, i.n, @"n property should be zero");
于 2013-09-02T18:12:13.327 回答
0

It takes the literal 0 as an int instead of an NSUInteger.

Use instead (NSUinteger)0

STAssertEquals((NSUInteger)0, i.n, @"n property should be zero");

To avoid discussions whether NSUInteger is unsigned log or unsigned int...this is from Apple NSObjCRuntime.h:

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

So in iOS is unsigned int and in other platforms could vary.

于 2013-09-02T18:05:05.320 回答
-1

Have you tried 0uL? NSUInteger is unsigned long.

于 2013-09-02T17:57:45.863 回答