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)

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top