5

I am writing an iOS 5 app which tracks a user's location in real-time, plotting their course on a MKMapView. Whenever a GPS reading is taken I would like a polyline to be drawn between the current and old locations, eventually forming a track (or breadcrumb) of where the user has travelled.

I am comfortable with using MKPolyline and MKPolylineView to draw a track, assuming that I have all the CLLocationCoordinate2D coordinates in advance, using code similar to below:

MKPolyline *route = [MKPolyline polylineWithCoordinates:coordinates count:[self.coordinateArray count]];        
[mapView addOverlay:route];

However, since I am only getting the CLLocationCoordinate2D coordinates in real-time (as the locationManager:didUpdateToLocation:fromLocation: delegate method is called) I am unsure of the best way to draw the new polylines.

Can I extend the existing lines (i.e. adding to the C-based coordinates array - not having much C experience I am unsure how to do this) or do I need to create a new polyline between the next two coordinates (although I have heard that having too many individual polylines on the map can impact performance and memory usage...)?

Thanks in advance.

Skoota
  • 5,280
  • 9
  • 52
  • 75
  • 1
    Have you seen the Apple sample app [Breadcrumb](http://developer.apple.com/library/ios/#samplecode/Breadcrumb/Introduction/Intro.html)? –  Apr 07 '12 at 12:53

1 Answers1

5

First, see how to update MKPolyline / MKPolylineView?, especially the link to the the Breadcrumb sample code. It may be a good starting point for what you need.

However, you'll see that a vital part of its CrumbPath object is a call to realloc. So yes, you need to know how to manage C-style arrays if you want to efficiently store your arrays of points. Yes, this is not easy. Yes, C-style array manipulation is an invitation for memory leaks.

The Breadcrumb sample uses realloc to resize its array. You can be a bit safer by allocating the memory the array uses with the NSMutableData type. It is recommended as an answer to Is it ok to use “classic” malloc()/free() in Objective-C/iPhone apps?. Read the other solutions to see regular C malloc() and free() functions doing the same job. Note that NSMutableData has a very handy increaseLengthBy: method.

When you understand why every C student attempts to use sizeof() incorrectly - and how to use it properly - you will understand C memory management.

Community
  • 1
  • 1
Cowirrie
  • 7,218
  • 1
  • 29
  • 42
  • Thanks for your reply (and pointing me towards the Breadcrumb sample code!). – Skoota Apr 08 '12 at 04:07
  • 1
    The Breadcrumb sample link is broken. I have found the new link: http://developer.apple.com/library/ios/#samplecode/Breadcrumb/Introduction/Intro.html – Sam Spencer Apr 28 '13 at 16:16