问题
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.
回答1:
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)
回答2:
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
回答3:
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.
回答4:
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]];
来源:https://stackoverflow.com/questions/1752701/how-to-convert-an-nsinteger-to-an-int