我担心引用,当我在 Objective-C 中调用方法时,我会避免对象的最大拷贝。
有人说Objective-C是按值传递对象,那么这个C++在Objective-C中还有可能吗?或者是否存在解决方法?
目前我看到的唯一解决方案是使用 Objective-C++。
最佳答案
在 Objective-C 中,所有对象都是在堆上创建的。因此所有对象都被引用。因此,没有对象被“静静地”复制,尤其是在传递给方法或函数时:
NSString *foo = @"bar"; // foo is a reference to a string object
doSomething( foo ); // a reference is passed
Objective-C 总是像 C 一样按值传递参数,但是因为它总是一个引用,所以引用被复制(通常是一个机器字)而不触及被引用对象的身份。
void doSomething( NSMutableString* foo ) // A function taking a reference to an instance of NSMutableString
{
[foo appendString:@"foobar"];
foo = nil;
}
NSMutableString *foo = [@"bar" mutableCopy]; // foo is a reference to an instance of NSMutableString
doSomething( foo ); // A copy of the reference, nor the object neither a copy of the object is passed
// foo is unchanged, since it is copied through pass by value.
// the object, foo points to, is @"barfoobar", since the object is not copied
所以没有什么可以避免的。
关于c++ - C++中 "const reference"的概念在Objective-C中是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761611/