Why don't I declare NSInteger with a *

こ雲淡風輕ζ 提交于 2019-11-28 05:14:43
Dan Lorenc

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.

NSInteger is just a typedef for int, AFAIK.

Working with pointers

NSInteger integer1 = 1;
NSLog(@"1. integer1:%ld &integer1:%p", integer1, &integer1);
//1. integer1:1 &integer1:0x7ffee59e8a98

NSInteger *integer2 = &integer1;
NSLog(@"2. integer2:%p &integer2:%p *integer2:%ld", integer2, &integer2, *integer2);
//2. integer2:0x7ffee59e8a98 &integer2:0x7ffee59e8a90 *integer2:1

*integer2 = 2;
NSLog(@"3. integer2:%p &integer2:%p *integer2:%ld \t integer1:%ld &integer1:%p", integer2, &integer2, *integer2, integer1, &integer1);
//3. integer2:0x7ffee59e8a98 &integer2:0x7ffee59e8a90 *integer2:2    integer1:2 &integer1:0x7ffee59e8a98
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!