开发者

How exactly does returning structs work in Objective-C?

Say 开发者_JAVA技巧I have the following function that returns a CLLocationCoordinate2D, which is just a struct that has two doubles (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;
}

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];

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.


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.


You are correct. If you browse the documentation, you will see:

typedef double CLLocationDegrees;

typedef struct {
   CLLocationDegrees latitude;
   CLLocationDegrees longitude;
} CLLocationCoordinate2D;


Yes, that is how you handle returning structures. When you use a method which returns a structure, the compiler modifies it so that it actually returns void, and adds a new first argument which is a pointer to the structure that the result should be stored in. So, your method is compiled more like this:

- (void):(CLLocationCoordinate2D*)returnValue getCoordinateForHouse:(House *)house
{
    CLLocationCoordinate2D coordToReturn;
    coordToReturn.latitude = // get house's latitude somehow
    coordToReturn.longitude = // get house's longitude somehow

    returnValue->latitude = coordToReturn.latitude;
    returnValue->longitude = coordToReturn.longitude;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜