When switching to a Mac from iOS to Objective-C, NSIntegers give type matching errors

I’ve been working on an iOS project for some time now, and recently I decided to port the code to a Mac project. Since I decided to use NSInteger in my code, and NSInteger is dependent on the typecast environment, this means that my variables are different types in iOS and Mac applications.

When I run the test suite on a Mac, all my STAssertEquals calls fail with a "Mismatch Type -" error because the types do not match:

NSInteger foo = 1; STAssertEquals(foo, 1, nil); // Test fails!! 

Mentioning my scalars works, but it seems really messy:

 NSInteger foo = 1; STAssertEquals(foo, (NSInteger)1, nil); // Succeeds, but is ugly!! 

Am I missing something? I'm starting to suspect that the decision to use NSIntegers was a bad choice.

Update: perhaps this article . It seems to support scanning scanning machines.

+6
source share
1 answer

Your use of NSInteger is probably the right choice, but causes some problems with STAssertEquals.

STAssertEquals fails if two objects have different types of Objective-C

Lone 1 will be interpreted by the C compiler as (signed int), which has an encoding of type "i".

These macros will also fail:

 unsigned u = 1; STAssertEquals(u, 1, nil); // Fails because u is type "I" (unsigned int) and 1 is type "i" (int) char c = 1; STAssertEquals(c, 1, nil); // Fails because c is type "c" (signed char) and 1 is type "i" (signed int) 

To make the compiler a different type for 1 , you must add a suffix, such as 1U for (unsigned int), 1UL for (unsigned long) or 1L for (long).

NSInteger is defined as the same size as pointers, which depends on the architecture of the device. On 32-bit Mac OS X and iOS, NSInteger is either type (signed int) or "i". On 64-bit Mac OS X, this is a long, or "q" type. (64-bit Mac OS X is an LP64 architecture, which means that L ongs and P are both types: 64- bit)

So the left side of your STAssertEquals is "q", while the right side is "i", causing a type mismatch.

Your decision to use (NSInteger) 1 seems to accurately reflect what you want - test the NSInteger variable with an NSInteger constant of value 1.

+5
source

Source: https://habr.com/ru/post/907363/


All Articles