Objective-c上的指针 [英] Pointers on Objective-c

查看:77
本文介绍了Objective-c上的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解(如果我错了,请纠正我):

From what I understand (and please correct me if I'm wrong):

int x, count = 10;
int *hello;
hello = &count;
x = *hello;

此处,变量x和count声明为整数类型.此外,变量count被赋值为10.

Here the variables x and count are declared to be of type integer. Additionally, the variable count is assigned the value of 10.

hello是一个指向整数的指针.您好然后分配计数的地址. 为了访问count的值,hello必须在其前面带有一个星号,即* hello.

hello is a pointer to type integer. hello is then assigned the address of count. In order to access the value of count, hello must have an asterisk in front of it, ie, *hello.

因此,为x分配了计数值(在本例中为10)的值.

So, x is assigned the value of whatever is in count and in this case, 10.

但是...

Fraction *myFraction = [[Fraction alloc] init];
[myFraction someMethod];

在这里,如果我理解正确,myFraction是指向Fraction类实例的指针.

Here, if I understand correctly, myFraction is a pointer to an instance of Fraction class.

myFraction指向(或为其分配地址)已分配内存并初始化的对象.

myFraction is pointing to (or rather assigned the address of) an object which has been assigned memory and initialised.

当然,为了访问myFraction指向的对象,我应该写:

Surely, in order to access the object that myFraction points to, I ought to write:

 [*myFraction someMethod];

鉴于x访问count值的方式(肯定是为了访问对象),应该这样写而不是:

Given the way in which x accessed the value of count, surely in order to access the object, one ought to write this and not:

[myFraction someMethod]; 

此外,如果我有

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str = @"Programming can be a headache";
NSLog (@"%@\n", str);

为什么将str视为上面的对象?还是str是一个对象,在这种情况下,为什么要使其指向NSString类的实例?当然,我应该能够将一个对象分配给str?

Why is str being treated as an object above? Or is str an object and in which case, why would I want to make it point to an instance of NSString class? Surely, I ought to be able to just assign an object to str?

推荐答案

目标c中所有对象的使用都是通过对象引用完成的,例如指针.

All the usage of objects in objective c is done through object references, e.g. pointers.

  • 使用Objective C语法,您可以在不取消引用对象的情况下对其进行处理,这与C/C ++有所不同.
  • str是类型NSString的对象引用(如myFraction),@"Programming can be a headache"也是类型NSString的对象引用,因此您可以将其分配给str.
  • The Objective C syntax lets you treat objects without dereferencing them, this is different than C / C++ for that matter.
  • str is an object reference of type NSString (as myFraction) and @"Programming can be a headache" is an object reference of type NSString as well, so you can assign it to str.

这篇关于Objective-c上的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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