How to convert An NSInteger to an int?
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 numbe开发者_如何学编程rs < 32 are used.
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)
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
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.
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]];
精彩评论