Objective-C方法是否支持“按值传递”?
Objective-C 方法是否支持“按值传递”?或者更具体地说:
- 传递到方法的参数的默认行为是按引用传递吗?
- 如果是,在某些情况下是否有任何变化 - 例如,如果参数只是一个基本 int 而不是一个对象? (或者这与 Objective-c 无关)
- 是否有一种方法支持基本变量(例如 int)的值传递?
- 是否有一个方法支持对象的值传递? (我假设这里没有,但为了完整性会问。当然,人们可以在消息中自己进行复制,但是对于这种方法,我认为这不是 Objective-C 方法为您提供的东西,即它是自己动手)
谢谢
Does objective-c methods support "pass by value"? Or perhaps to be more specific:
- Is the default behavior for parameters passed into a method pass-by-reference?
- 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)
- Is there anyway to have a method support pass-by-value for a basic variable such as int?
- 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Objective-C 不支持引用,至少在 C++ 意义上不支持。
所有 Objective-C 对象都在堆上分配,因此所有“对象变量”实际上必须是指针类型。指针是否可以被认为实际上等同于引用是有争议的。例如,当谈论 C++ 时,存在明显的语义差异(否则,有什么意义......)
所以回答你的问题:
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:
没有。默认情况下,它是按值传递的,就像在 C 中一样。除了 Objective C 类实例引用之外,值是一个引用。因此,Objective C 类实例是通过引用有效传递的。
不适用
参见 1。
并非如此。您可以序列化、传递字符串并在内部重新创建。或者,您可以让对象将其 ivar 存储为结构并按值传递该结构。有些对象支持克隆。
No. It's pass-by-value by default, like in C. Except for the fact that for the Objective C class instance references, the value is a reference. So Objective C class instances are passed effectively by reference.
N/A
See 1.
Not really. You can serialize, pass the string, and recreate inside. Or you can have the object store its ivars as a structure and pass that structure by value. Some objects support cloning.