问题
我的 MKMapView 有问题。当我初始化它并尝试添加一些注释时,应用程序崩溃,给我一个 SIGABRT 并声称我有一个“未捕获的异常‘NSInvalidArgumentException’,原因:‘-[ __NSCFSet addObject:]: attempt to insert nil'"我弄乱了 NSLogs 和我的代码,发现每当我调用 [mapView addAnnotation:myAnnotation] 时它就会发生。我已经分别尝试了这两个注释,但应用程序仍然崩溃。
代码
这是我用于 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
理论
我尝试隔离 initMap,以便在我的任何其他应用程序加载之前调用它。稍后我还有其他进程在运行,但此时它们不应该处于事件状态,因为它们尚未初始化。我想这个问题可能与我对 MKMapView 本身的初始化有关,或者与我的 Displaymap 属性有关。 Xcode 无法检测到它,无论它是什么,我什至不确定我得到的错误是什么意思。
最佳答案
从您的代码来看,您似乎从未实例化过 thing1
和 thing2
。
尝试在 init 函数的开头添加这些行。
thing1 = [[DisplayMap alloc] init];
thing2 = [[DisplayMap alloc] init];
仅仅因为这些成员是属性并不意味着它们是自动初始化的。
关于ios - 添加注释时 MKMapView 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363771/