Why don't I declare NSInteger with a *
NSInteger
is a primitive type, which means it can be stored locally on the stack. You don't need to use a pointer to access it, but you can if you want to. The line:
NSInteger *processID = [[NSProcessInfo processInfo] processIdentifier];
returns an actual variable, not its address. To fix this, you need to remove the *
:
NSInteger processID = [[NSProcessInfo processInfo] processIdentifier];
You can have a pointer to an NSInteger
if you really want one:
NSInteger *pointerToProcessID = &processID;
The ampersand is the address of operator. It sets the pointer to the NSInteger
equal to the address of the variable in memory, rather than to the integer in the variable.
The reason that you don't declare NSInteger
with a *
is because it isn't an object. An NSInteger is simply an int
or a long
:
#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
endif
If it's being used in a 32-bit application, it's a 32-bit integer, and if it's being built in a 64-bit application, it's a 64-bit integer.
Of course, you can pass an NSInteger
as a pointer, but most functions simply take arguments as an NSInteger
and not a pointer to it.
Objects, on the other hand, can only be passed to other functions as pointers. This is because objects have memory dynamically allocated for them, and so cannot be declared on the stack. Since an int
or long
has a fixed amount of memory allocated for them, this is not an issue.
The *
means “pointer”. The object variable holds a pointer to an object, so it has a *
; the NSInteger variable holds an NSInteger, not a pointer to an NSInteger, so it does not have a *
. Putting the *
on that variable gives you at least a warning because you're putting an integer into a pointer variable.