Converting int to NSInteger [duplicate]
Asked Answered
H

1

25

Possible Duplicate:
How to convert An NSInteger to an int?

I am new to iOS programming, how do I convert int to NSInteger. I have found references on how to convert NSInteger to NSNumber but I wasn't able to figure it out. Any help would be appreciated. Thanks.

Hereto answered 22/11, 2011 at 12:0 Comment(4)
#1753201Suchta
Not a dupe, I believe, at least not of the proposed original. Converting apples into apple sauce is not the same as trying to convert apple sauce back into an apple :-)Pescara
This isn't how to turn apple sauce into apples, @paxdiablo, it's how to turn apples into Malus domesticae.Guyer
Why is this marked as a duplicate? Two different questions. Casting from int (32bit) to NSInt (64bit) is easy and automatic, this is asking how to cast from NSInt(64) to int(32). Re-open.Whop
M
62

An improved answer

On 64-bit systems NSInteger is long. On 32-bit systems NSInteger is int. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Cocoa64BitGuide/64BitChangesCocoa/64BitChangesCocoa.html

All you need just cast your int to NSInteger.

int i = 1;
NSInteger nsi = (NSInteger) i;

You can also cast NSInteger to int (as in an original answer), but you must be careful on 64-bit system, because your NSInteger can exceed int limits.

An original answer

int i;
NSInteger nsi = 1;
i = nsi;

No big science. :)

Mayoralty answered 22/11, 2011 at 12:3 Comment(4)
In which way does this explain how to create an NSInteger from an int?Belvia
@kb You are right! My original answer showed only how to cast NSInteger to int. I have improved my answer to include a more precise answer to the question.Mayoralty
This just saved me hours of finding a bug after updating an iOS app to support 64Bit Architecture.Soule
Suppress cast warning in 64 base system using #pragma clang diagnostic ignored "-Weverything"Whop

© 2022 - 2024 — McMap. All rights reserved.