Objective-C是按值传递还是按引用传递? [英] Is Objective-C pass-by-value or pass-by-reference?

查看:83
本文介绍了Objective-C是按值传递还是按引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我们总是使用指针来定义变量,所以我想知道Objective-C是否按值传递",因为像Java一样,实际值将通过使用其引用传递.

但是,由于它似乎建立在C之上,因此它具有C的所有功能吗?

解决方案

C不支持按引用传递和Objective-C,因为严格的C超集也不支持. /p>

在C语言(和Objective-C语言)中,您可以通过传递指针来模拟按引用传递,但是请记住,从技术上讲,您仍然在传递值,这一点很重要指针的值.

因此,在Objective-C(和C)中,没有其他语言(例如C ++或Java)所期望的引用概念.

这可能会造成混淆,所以让我尝试更加清楚(我将使用纯C,但是-再次-它在Objective-C中不会更改)

void increment(int *x) {
   *x++;
}

int i = 42;
increment(&i); // <--- this is NOT pass-by-reference.
               //      we're passing the value of a pointer to i

另一方面,在C ++中我们可以做到

void increment(int &x) {
   x++;
}

int i = 41;
increment(i); // <--- this IS pass-by-reference
              //      doesn't compile in C (nor in Objective-C)

Since we always use pointers to define variables, I was wondering if Objective-C is "pass by value", since like Java, the actual value would be passed by using its reference.

However, since it seems to be built up on top of C, would it have all the functionality of C?

解决方案

C does not support pass-by-reference and Objective-C, being a strict superset of C doesn't either.

In C (and Objective-C) you can simulate pass-by-reference by passing a pointer, but it's important to remember that you're still technically passing a value, which happens to be a the value of a pointer.

So, in Objective-C (and C, for the matter) there is no concept of reference as intended in other languages (such as C++ or Java).

This can be confusing, so let me try to be clearer (I'll use plain C, but - again - it doesn't change in Objective-C)

void increment(int *x) {
   *x++;
}

int i = 42;
increment(&i); // <--- this is NOT pass-by-reference.
               //      we're passing the value of a pointer to i

On the other hand in C++ we could do

void increment(int &x) {
   x++;
}

int i = 41;
increment(i); // <--- this IS pass-by-reference
              //      doesn't compile in C (nor in Objective-C)

这篇关于Objective-C是按值传递还是按引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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