Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does objective-c methods support "pass by value"?

Does objective-c methods support "pass by value"? Or perhaps to be more specific:

  1. Is the default behavior for parameters passed into a method pass-by-reference?
  2. If yes, are there any variations from this in some circumstances - for example if the parameter is just a basic int as opposed to an object? (or is this not relevant in objective-c)
  3. Is there anyway to have a method support pass-by-value for a basic variable such as int?
  4. Is there anyway to have a method support pass-by-value for an object? (I'm assuming no here, but for completeness will ask. Of course one could within the message do the copy yourself, however for this approach I'll consider this not to be something objective-c methods offers you, i.e. rather it was a do-it-yourself)

thanks

like image 654
Greg Avatar asked Mar 09 '11 20:03

Greg


1 Answers

Objective-C does not support references, at least not in the C++ sense of the term.

All Objective-C objects are allocated on the heap, and therefore all "object variables" must in fact be pointer types. Whether a pointer can be considered to be effectively the equivalent of a reference is open to debate. When talking C++ for example, there are clear semantic differences (otherwise, what's the point...)

So to answer your questions:

  1. No, Objective-C only supports pass-by-value. If you pass an object pointer to a method, you pass the pointer by value - you are not passing a reference.
  2. There is no inherent difference between objects and primitives in this regard, apart from the fact that objects are always referred to by pointer, never by value. You can pass a primitive type pointer in if you like.
  3. Yes. This is always the case. Again, if you pass in a pointer to a primitive, you are passing a pointer by value, not a reference.
  4. You're pretty much bang on the mark with this one, other than the fact that you're passing around pointers, not references.
like image 94
Mac Avatar answered Oct 13 '22 00:10

Mac