Why don't structs return a pointer? (CLLocationCoordinate2D)


#1

Hey everyone.
I’m completely new to iOS and Objective-C but this book is proving to be a very good read. I just have a quick question about the CLLocationCoordinate2D implementation here. When creating the class, I typed:

@interface MapPoint : NSObject <MKAnnotation> { NSString *title; CLLocationCoordinate2D coordinate; }

I understand what this does and how we implement it, but one thing I’m still unsure about is why ‘coordinate’ is not a pointer like ‘*title’? I looked in the documentation and it’s TypeDef struct which is why we don’t actually type it as a pointer, but why is it implemented like that? Why are TypeDef structs not returning pointers, but other classes do (such as Possesson *p from the previous chapters)? I’m probably missing something obvious, so thanks for any help! :slight_smile:


#2

There are a number of attributes about Objective-C objects that require they live by themselves on the heap. That is, no object’s memory can be inside another object. You also cannot create an object on the stack. Every reference to an object is through a pointer that points to its place in memory.

Structures are different. Structures don’t have any of the fancy stuff that an object has, like being able to receive messages or reference counting. Instead, structures are just a chunk of memory. You can create “instances” of a structure on the stack just fine (the memory for the structure will be freed automatically when the method finishes) and a structure can be an instance variable of an object because it will automatically be destroyed when the object is destroyed.


#3

Great explanation, thanks a lot! :slight_smile: