How to convert An NSInteger to an int?

Objective CCocoaNsinteger

Objective C Problem Overview


For example when passing a value message to an NSInteger instance like so

[a value] it causes an EXC_BAD_ACCESS.

So how to convert an NSInteger to int?

If it's relevant only small numbers < 32 are used.

Objective C Solutions


Solution 1 - Objective C

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

Solution 2 - Objective C

If you want to do this inline, just cast the NSUInteger or NSInteger to an int:

int i = -1;
NSUInteger row = 100;
i > row // true, since the signed int is implicitly converted to an unsigned int
i > (int)row // false

Solution 3 - Objective C

I'm not sure about the circumstances where you need to convert an NSInteger to an int.

NSInteger is just a typedef:

NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

You can use NSInteger any place you use an int without converting it.

Solution 4 - Objective C

Commonly used in UIsegmentedControl, "error" appear when compiling in 64bits instead of 32bits, easy way for not pass it to a new variable is to use this tips, add (int):

[_monChiffre setUnite:(int)[_valUnites selectedSegmentIndex]];

instead of :

[_monChiffre setUnite:[_valUnites selectedSegmentIndex]];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffreyView Question on Stackoverflow
Solution 1 - Objective CDave DeLongView Answer on Stackoverflow
Solution 2 - Objective CSamuel ClayView Answer on Stackoverflow
Solution 3 - Objective CAbizernView Answer on Stackoverflow
Solution 4 - Objective CgrominetView Answer on Stackoverflow