为什么我不声明NSInteger与* [英] Why don't I declare NSInteger with a *

查看:187
本文介绍了为什么我不声明NSInteger与*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iTunes U上的斯坦福大学的iPhone课程尝试我的手,我对指针有点困惑。在第一个任务中,我试着做这样的事情。

I'm trying my hand at the iPhone course from Stanford on iTunes U and I'm a bit confused about pointers. In the first assignment, I tried doing something like this

NSString *processName = [[NSProcessInfo processInfo] processName];
NSInteger *processID = [[NSProcessInfo processInfo] processIdentifier];

这产生了一个错误,在盲目摸索之后,我发现它是NSInteger行中的*这是造成这个问题。

Which generated an error, after tinkeing around blindly, I discovered that it was the * in the NSInteger line that was causing the problem.

所以我显然不明白发生了什么。我会解释我如何认为它的工作,也许有人会很好的指出缺点。

So I obviously don't understand what's happening. I'll explain how I think it works and perhaps someone would be kind enough to point out the flaw.


与在web开发中不同,我现在需要
来担心内存,更好的是在web开发中。所以当I
创建一个变量时,它会分配一个
位的内存(RAM I
)。而不是传递
变量,我传递一个指针到
的内存位。并且
指针通过用*标记
变量名前缀来声明。

Unlike in web development, I now need to worry about memory, well, more so than in web development. So when I create a variable, it gets allocated a bit of memory somewhere (RAM I assume). Instead of passing the variable around, I pass a pointer to that bit of memory around. And pointers are declared by prefixing the variable name with *.

假设我是对的,难道我是为什么我不需要这样做NSInteger?

Assuming I'm right, what puzzles me is why don't I need to do that for NSInteger?

推荐答案

NSInteger 是一个原始类型,这意味着可以本地存储在堆栈。你不需要使用指针访问它,但你可以如果你想。行:

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];

您可以有一个 NSInteger 如果你真的想要一个:

You can have a pointer to an NSInteger if you really want one:

NSInteger *pointerToProcessID = &processID;

&符号是运算符的地址。它设置指向 NSInteger 的指针等于内存中变量的地址,而不是变量中的整数。

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.

这篇关于为什么我不声明NSInteger与*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆