返回值的访问器与返回引用的访问器?
根据我的理解,以下两个 getter 方法都引用实际对象。 那么两者有什么区别呢?
什么时候以及为什么要使用第二个 getter 方法?
- (MyObject *)myObject
{
return _myObject;
}
- (void)getMyObject:(MyObject **)myObject
{
if (!myObject)
{
*myObject = _myObject;
}
}
From my understanding both of the following getter methods reference the actual object.
So what is the difference between the two?
When and why would you want to use the second getter method?
- (MyObject *)myObject
{
return _myObject;
}
- (void)getMyObject:(MyObject **)myObject
{
if (!myObject)
{
*myObject = _myObject;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不会使用第二个。
除非您喜欢在以后因不遵循标准约定而让别人/您自己感到困惑。
如果还可以返回另一条数据,则更有意义,例如查看
NSManagedObjectContext
该方法的重要结果是
YES
/NO< /code> 保存了它,但是我们还可以获取一个
NSError
对象来检查是否存在错误。You would not use the second one.
Unless you like confusing people/yourself at a later date by not following the standard conventions.
It would make more sense if there was another piece of data that could also be returned for example look at
NSManagedObjectContext
The important result of the method is
YES
/NO
did it save, but then we can also get anNSError
object to inspect if there was an error.在 Objective C 中,“对象”是一个 C 指针,因此对象值实际上已经与结构引用相同(如果您希望代码在 Objective C 运行时之间可移植,则为具有隐藏字段的不透明结构)。
所以不存在“对”。
你的第一个例子都是两者。
在某些特殊情况下,算法需要引用到引用或指针到指针,但这种情况并不常见。那将是你的第二个例子。
In Objective C, an "object" is a C pointer, so an object value is actually already the same as a structure reference (an opaque structure with hidden fields if you want the code to be portable between Objective C runtimes).
So there is no "versus".
YouR first example is both.
There are special situations when an algorithm needs a reference to a reference, or a pointer to a pointer, but not very commonly. That would be your second example.