Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between int and NSInteger? [duplicate]

Possible Duplicates:
When to use NSInteger vs int?
Why is there is an NSInteger?

Can we use int and NSInteger interchangably? Is there any specific situation to use NSInteger only, instead of using int?

like image 589
Prasad Avatar asked May 19 '11 09:05

Prasad


People also ask

What is NSInteger?

NSInteger is a simply an integer, NSNumber is an object where as int is a primitive data type.

How many bits is NSInteger?

When building 32-bit applications, NSInteger is a 32-bit integer.

Is int always 32 bits?

int is always 32 bits wide. sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T .

Is NSInteger primitive?

It is not a C primitive (like int, unsigned int, float, double, etc.) NSInteger , CGFloat , NSUInteger are simple typedefs over the C primitives.


2 Answers

Can we use int and NSInteger interchangably?

No. On the LP64 architecture used by Apple, for modern OS X Cocoa, NSInteger is 64 bits wide. This means that if you cast an NSInteger to an int, comparisons against NSNotFound may fail. Here's an example:

NSRange theRange = [@"foo" rangeOfString @"x"];
int location = theRange.location;
if (location == NSNotFound) // comparison is broken due to truncation in line above
{
    // x not in foo
}

In my opinion, you should only use NSInteger where you need to pass a parameter to Cocoa or receive a result from Cocoa and the documentation says the data type is NSInteger. In all other cases:

  • if you don't care about the width of the type, use a C type e.g. int or long.
  • if you do care about the width of the type, use the C99 stdint.h types e.g. int32_t, int64_t.
  • if you need an int guaranteed big enough to hold a pointer, use intptr_t or uintptr_t
like image 128
JeremyP Avatar answered Oct 06 '22 13:10

JeremyP


I would say use standard C99 uintptr_t for pointer sized integers. The definition of NSInteger looks sufficiently cloudy not to be sure it is guaranteed to hold a pointer.

Use NSInteger where the API uses it, if you must. But long will do for all practical purposes.

Looking at NSObjCRunTime, I don't really get the motivation for its current definition. Probably to have an integer type large enough to go up to, for instance, the maximum number of items in an NSArray?

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
like image 33
Steven Kramer Avatar answered Oct 06 '22 12:10

Steven Kramer