Is Objective-C pass-by-value or pass-by-reference?

混江龙づ霸主 提交于 2019-12-18 00:29:26

问题


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?


回答1:


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)



回答2:


It is a strict superset of C. It does the same as C. It's one reason all Objects are actually pointers to structs.



来源:https://stackoverflow.com/questions/22213197/is-objective-c-pass-by-value-or-pass-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!