How do I convert NSUInteger value to int value in objectiveC? [duplicate]
Asked Answered
S

4

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

Sagittate answered 10/5, 2013 at 12:7 Comment(1)
It's %lu, not @lu.Kathlyn
W
82
NSUInteger intVal = 10;
int iInt1 = (int)intVal;
NSLog(@"value : %lu %d", (unsigned long)intVal, iInt1);

for more reference, look here

Whelk answered 10/5, 2013 at 12:15 Comment(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);.Stereochrome
W
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);
Whitmire answered 10/5, 2013 at 12:14 Comment(0)
S
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..

Sagittate answered 10/5, 2013 at 12:24 Comment(4)
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.Whitmire
@SteveWaddicor You have other problems when your inbox contains > 2 billion Mails.Stereochrome
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.Whitmire
@SteveWaddicor I totally agree. It's just the specifics of this case that made me make this little joke.Stereochrome
A
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

Armageddon answered 10/5, 2013 at 12:11 Comment(1)
Explain the down-vote please...Armageddon

© 2022 - 2024 — McMap. All rights reserved.