Domanda

I have heard that people use types such as NSInteger or CGFloat rather than int or float is because of something to do with 64bit systems. I still don't understand why that is necessary, even though I do it throughout my own code. Basically, why would I need a larger integer for a 64bit system?

People also say that it is not necessary in iOS at the moment, although it may be necessary in the future with 64bit iphones and such.

È stato utile?

Soluzione 2

Essentially it boils down to this: If you use CGFloat/NSInteger/etc, Apple can make backwards-incompatible changes and you can mostly update your app by just recompiling your code. You really don't want to be going through your app, checking every use of int and double.

What backwards-incompatible changes? Plenty!

  • M68K to PowerPC
  • 64-bit PowerPC
  • PowerPC to x86
  • x86-64 (I'm not sure if this came before or after iOS.)
  • iOS

CGFloat means "the floating-point type that CoreGraphics" uses: double on OS X and float on iOS. If you use CGFloat, your code will work on both platforms without unnecessarily losing performance (on iOS) or precision (on OS X).

NSInteger and NSUInteger are less clear-cut, but they're used approximately where you might use ssize_t or size_t in standard C. int or unsigned int simply isn't big enough on 64-bit OS X, where you might have a list with more than ~2 billion items. (The unsignedness doesn't increase it to 4 billion due to the way NSNotFound is defined.)

Altri suggerimenti

It is all explained here:

Introduction to 64-Bit Transition Guide

In the section Major 64-Bit Changes:

enter image description here

Data Type Size and Alignment

OS X uses two data models: ILP32 (in which integers, long integers, and pointers are 32-bit quantities) and LP64 (in which integers are 32-bit quantities, and long integers and pointers are 64-bit quantities). Other types are equivalent to their 32-bit counterparts (except for size_t and a few others that are defined based on the size of long integers or pointers).

While almost all UNIX and Linux implementations use LP64, other operating systems use various data models. Windows, for example, uses LLP64, in which long long variables and pointers are 64-bit quantities, while long integers are 32-bit quantities. Cray, by contrast, uses ILP64, in which int variables are also 64-bit quantities.

In OS X, the default alignment used for data structure layout is natural alignment (with a few exceptions noted below). Natural alignment means that data elements within a structure are aligned at intervals corresponding to the width of the underlying data type. For example, an int variable, which is 4 bytes wide, would be aligned on a 4-byte boundary.

There is a lot more that you can read in this document. It is very well written. I strongly recommend it to you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top