0

I'm new to Objective C so this could be very stupid question. I was reading iOS Programming book and came upon this snippet of code:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    CLLocationCoordinate2D loc = [userLocation coordinate]; // returns CLLocationCoordinate2D
    ...
}

I'm still learning Objective C, but shouldn't loc be a pointer? From what I understand you can only assign directly simple types like int and float. Here CLLocationCoordinate2D is a structure. And yet this doesn't work:

CLLocationCoordinate2D *loc = [userLocation coordinate]; 
// this throws error message
// Initializing 'CLLocationCoordinate2D *' with an expression of incompatible type 'CLLocationCoordinate2D'

So what's going on here and how can I learn more about pointers. Thanks!

mgs
  • 2,621
  • 2
  • 19
  • 14

3 Answers3

2

structures are not pointers!

They are just simple C-type data structure like int, float, etc..

Burhanuddin Sunelwala
  • 5,318
  • 3
  • 25
  • 51
1

It depends on what the return type of [userLocation coordinate] is. If it returns a structure then you have to store that structure somewhere. In this case you will store it on the stack and it will be removed once it runs out of scope.

If it returned a pointer then that pointer would point to where the structure was stored. Keep in mind that structs are not objects, they are just a record that can store multiple values grouped together.

  • Right - it returns a structure, not a pointer to a structure: @property(readonly, NS_NONATOMIC_IPHONEONLY) CLLocationCoordinate2D coordinate – bryanmac Apr 08 '13 at 11:51
1

You can assign a scruct. Objectiv-C is still C in the end.

Although internally an object in memory is not quite different from a structure, you cannot directly assign objects but references to objects.

So you need to be aware of what [userLocation coordinate] really returns. It could be a structure or a pointer to a structure or an id alike. Therefore your local varialbe that receives the return value must be of the same type.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71
  • Thank you, seems like I need to learn C better. – mgs Apr 08 '13 at 12:01
  • Well, from start I would say no. It can be confusing knowing C too well when working with Obj-C as newbie to both languages. On the other hand, whenever you find strange syntaxes, the answer is in the C layer. :) – Hermann Klecker Apr 08 '13 at 15:46