Problem
I am having a problem with my MKMapView.When I initialize it and try to add a couple annotations, the app crashes, giving my a SIGABRT and claiming that I have an “uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSCFSet addObject:]: attempt to insert nil'” I have messed around with NSLogs and my code and found that it occurs whenever I call [mapView addAnnotation:myAnnotation]. I have tried both annotations individually and the app still crashes.
Code
Here is the code I am using for my MKMapView
IBOutlet MKMapView *mapView; //these are in interface
DisplayMap *thing1; //yes, I have @properties too, and I synthesize them
DisplayMap *thing2;
-(void) initMap //called in viewDidLoad after [super viewDidLoad]
{
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation = YES;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = 0;
region.center.longitude = 0;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
thing1.title = @"thing1";
thing1.subtitle = @"is here";
thing1.coordinate = region.center;
thing2.title = @"thing2";
thing2.subtitle = @"is somewhere";
CLLocationCoordinate2D thing2Coord = {0.005,0.005};
thing2.coordinate = thing2Coord;
[mapView addAnnotation:thing1];
[mapView addAnnotation:thing2];
}
//and my DisplayMap code
//the .h
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
@interface DisplayMap : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end
//the .m
#import "DisplayMap.h"
@implementation DisplayMap
@synthesize coordinate,title,subtitle;
-(void)dealloc{
[title release];
[subtitle release];
[super dealloc];
}
@end
Theories
I tried to isolate initMap so that it is called before any of the rest of my app loads. I have other processes running later, but they should not be active at this point because they have not been initialized yet. I imagine the problem could have something to do with my initialization of the MKMapView itself, or in my Displaymap properties. Xcode can’t detect it, whatever it is, and I’m not really sure what the error I’m getting even means.
From your code, it doesn’t look like you are ever instantiating
thing1andthing2.Try adding these lines at the beginning of your init function.
Just because these members are properties doesn’t mean that they are auto-initialized.