Whats mentioned here so far hasn't quite worked for me but I managed a solution based on the other answers and some independent research. I am not 100% certain in this but you can cast a MKPolyline into a custom sub-class only if you use the static method call that calls the right 'init' method internally.
(CustomPolyline*)[CustomPolyline polylineWithCoordinates:coordinates count:coordinateCount]
The above won't work because polylineWithCoordinates
only allocates memory for an MKPolyline
object and not CustomPolyline
. I suspect what's happening internally is that polylineWithCoordinates
calls another initializer method in a manner similar to: [MKPolyline otherInitMethod:...]
. And its not allocating the proper amount of memory because its now using an MKPolyline
static method call and not our CustomPolyline
static call.
However if we use
(CustomPolyline*)[CustomPolyline polylineWithPoints:polyline.points count:polyline.pointCount];
It does work. I think this is because polylineWithPoints
is using an initializer that returns an id
not just chaining to another method call. And since we called it using the CustomPolyline
class the initializer allocates memory for CustomPolyline
not MKPolyline
.
I could be completely wrong on why it works. But I've tested this and it seems to work fine. MKPolygon
can be extended in a similar manner. In that case I think the correct static method to use is MKPolygon polygonWithCoordinates:points count:pointSet.count]]
My implementation for reference:
CustomPolyline.h
#import <MapKit/MapKit.h>
typedef enum {
CustomPolylineTypeNone = 0,
CustomPolylineDifferentStrokes
} CustomPolylineType;
/**
* CustomPolyline wraps MKPolyline with additional information about a polyline useful for differentiation.
*/
@interface CustomPolyline : MKPolyline
@property CustomPolylineType type;
-(CustomPolyline*)initWithMKPolyline:(MKPolyline*)polyline;
@end
CustomPolyline.m
#import "CustomPolyline.h"
@implementation CustomPolyline
@synthesize type;
/**
* Takes an MKPolyline and uses its attributes to create a new CustomPolyline
*/
-(CustomPolyline*)initWithMKPolyline:(MKPolyline*)polyline
{
// We must use the this specific class function in this manner to generate an actual
// CustomPolyline object as opposed to a MKPolyline by a different name
return (CustomPolyline*)[CustomPolyline polylineWithPoints:polyline.points count:polyline.pointCount];
}
@end