返回结构在 Objective-C 中究竟是如何工作的? [英] How exactly does returning structs work in Objective-C?
问题描述
假设我有以下函数返回一个 CLLocationCoordinate2D
,它只是一个 struct
,它有两个 double
(名为 经度
和纬度
):
Say I have the following function that returns a CLLocationCoordinate2D
, which is just a struct
that has two double
s (named longitude
and latitude
) in it:
- (CLLocationCoordinate2D)getCoordinateForHouse:(House *)house
{
CLLocationCoordinate2D coordToReturn;
coordToReturn.latitude = // get house's latitude somehow
coordToReturn.longitude = // get house's longitude somehow
return coordToReturn;
}
我可以基本上像对待任何其他原始类型一样对待这个 struct
吗?例如,如果我在其他地方的代码中调用上面的函数,如下所示:
Can I basically treat this struct
just like any other primitive type? For instance, if I call the function above in code somewhere else like this:
CLLocationCoordinate2D houseCoord =
[someClassThatTheAboveFunctionIsDefinedIn getCoordinatesForHouse:myHouse];
从函数返回的值被简单地复制到 houseCoord
(就像任何其他原语一样),对吗?我不必担心 CLLocationCoordinate2D
在其他地方被破坏?
The value that was returned from the function is simply copied into houseCoord
(just like any other primitive would act), right? I don't have to worry about the CLLocationCoordinate2D
ever being destroyed elsewhere?
现在这对我来说似乎很明显,但我只需要确认.
Seems obvious to me now that this is probably the case, but I just need confirmation.
推荐答案
这是 Objective-C 直接从 C 继承其行为的领域——分配结构会导致浅拷贝.所以如果你在结构中有任何指针,那么你将复制指针,而不是指向的东西.在 C 代码中,您需要将其纳入有关所有权的临时规则.在 Objective-C 中,自动引用计数编译器无法处理对结构(或者,我认为,联合)内对象的引用,因此在任何情况下都不要太执着于这个想法是明智的.
This is an area where Objective-C inherits its behaviour directly from C — assigning structs causes a shallow copy. So if you have any pointers inside the structs then you'll copy the pointer, not the thing pointed to. In C code you need to factor that in to your adhoc rules about ownership. In Objective-C the automatic reference counting compiler isn't capable of dealing with references to objects within structs (or, I think, unions) so it's smart not to become too attached to the idea in any event.
这篇关于返回结构在 Objective-C 中究竟是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!