30

How do I convert NSUInteger value to int value in objectiveC?

and also how to print NSUInteger value in NSLog , I tried %@,%d,%lu these are not working and throwing Ex-Bad Access error.

Thank you

rmaddy
  • 314,917
  • 42
  • 532
  • 579
GR.
  • 455
  • 1
  • 4
  • 18

4 Answers4

82
NSUInteger intVal = 10;
int iInt1 = (int)intVal;
NSLog(@"value : %lu %d", (unsigned long)intVal, iInt1);

for more reference, look here

Girish
  • 4,692
  • 4
  • 35
  • 55
  • 1
    Apple's documentation (your link) explicitly states "Cast the value to unsigned long." for `NSUInteger`. So the last line should be `NSLog(@"the value is : %lu %d", (unsigned long)intVal, iInt1);`. – Nikolai Ruhe May 10 '13 at 12:33
4

Explicit cast to int

NSUInteger foo = 23;
int bar = (int)foo;

Although

NSLog(@"%lu",foo);

will work OK on current builds of OSX. It's not safe, as NSUInteger is typedeffed as unsigned int on other builds. Such as iOS. The strict answer is to cast it first:

NSLog(@"%lu",(unsigned long)foo);
Steve Waddicor
  • 2,197
  • 15
  • 20
1

Hi all its working for me ...

I tried this..

NSUInteger  inbox_count=9;
NSLog(@"inbox_count=%d",(int)inbox_count);

//output   
inbox_count=9

thank to all..

Thilina Chamath Hewagama
  • 9,039
  • 3
  • 32
  • 45
GR.
  • 455
  • 1
  • 4
  • 18
  • Bad idea. On OSX, NSUInteger is long. So casting to int will overflow for large values. It might be OK for iOS, but better to get used to doing it in a way that doesn't break on other builds. – Steve Waddicor May 10 '13 at 12:38
  • 2
    @SteveWaddicor You have other problems when your inbox contains > 2 billion Mails. – Nikolai Ruhe May 10 '13 at 12:46
  • The specifics of this case are not the limits of a stackoverflow answer. Someone else may try to apply the broken code for a number that can get that big. Better to do it right, when doing it wrong is no easier. – Steve Waddicor May 10 '13 at 12:49
  • @SteveWaddicor I totally agree. It's just the specifics of this case that made me make this little joke. – Nikolai Ruhe May 10 '13 at 12:54
0

It's simple as this,

NSUInteger uintV = 890;
int intVal = (int) uintV;
NSLog(@"the value is : %lu", (unsigned long)intVal);


this will print something like this,
the value is : 890

Thilina Chamath Hewagama
  • 9,039
  • 3
  • 32
  • 45