Reputation: 535138
I created a minimal custom MKAnnotation in Swift:
import UIKit
import MapKit
class MyAnnotation : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String = ""
var subtitle: String = ""
init(location coord:CLLocationCoordinate2D) {
self.coordinate = coord
super.init()
}
}
And I add it to my MKMapView in the normal way:
let ann = MyAnnotation(location:self.annloc)
self.map.addAnnotation(ann)
The annotation appears on the map. (I also have a custom MKAnnotationView, but that's irrelevant.) But there's a problem; the annotation is not really there. By this I mean that when I ask for the map's annotations array, self.map.annotations
, it is empty.
This appears to be purely a Swift problem. If I replace MyAnnotation with an Objective-C implementation, changing nothing else about my project, it works perfectly! This MyAnnotation does show up in self.map.annotations
as expected:
// === .h file:
#import <Foundation/Foundation.h>
@import MapKit;
@interface MyAnnotation : NSObject <MKAnnotation>
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title, *subtitle;
- (id)initWithLocation:(CLLocationCoordinate2D)coord;
@end
// === .m file:
#import "MyAnnotation.h"
@implementation MyAnnotation
- (id)initWithLocation: (CLLocationCoordinate2D) coord {
self = [super init];
if (self) {
self->_coordinate = coord;
}
return self;
}
@end
The problem is an obscure one, and you may be using a custom MKAnnotation written in Swift without realizing there's any issue. But the issue is real and can cause trouble down the road.
So what we know very clearly is that an MKAnnotation written in Swift doesn't work and the very same MKAnnotation written in Objective-C does. The question is: why? And secondarily: can we do anything about it? Is it possible to write an MKAnnotation in pure Swift that will show up properly in the map's annotations
array?
I'm guessing that the problem is either something to do with KVC or something to do with the fact that, let's face it, a Swift object just isn't quite the same thing as an Objective-C object. I've tried addition various KVC-like features, dynamic
, etc. to my Swift version of MKAnnotation but nothing seems to help.
Upvotes: 2
Views: 2045
Reputation: 535138
This must have been a bug in Swift at the time I wrote the question, because now (Xcode 6.3) the issue is gone — the problem is fixed.
Upvotes: 1