我正在尝试使用路径数据库中的纬度和经度来推送到地图应用,并将用户从当前位置引导到路径。 API采用JSON格式。这是我在模型类中的自定义init方法:
- (instancetype)initWithDictionary:(NSDictionary *)dict
{
self = [super init];
if (self) {
self.latitude = dict[@"lat"];
self.longitude = dict[@"lon"];
self.name = dict[@"name"];
self.city = dict[@"city"];
self.state = dict[@"state"];
self.country = dict[@"country"];
self.described = dict[@"description"];
self.directions = dict[@"directions"];
self.activities = dict[@"activity_type_name"];
}
return self;
}
以下是该类的坐标属性:
@property (nonatomic, assign) NSNumber *latitude;
@property (nonatomic, assign) NSNumber *longitude;
当应用调用directToTrail方法时,应用程序崩溃,代码在coordinate.latitude分配处显示<Thread 1: EXC_BAD_ACCESS (code=EXC_1386_GPFLT)>
。以下是我的自定义单元类中该方法的代码。
- (void)directToTrail:(Trail *)trail
{
CLLocationCoordinate2D coordinate;
coordinate.latitude = (CLLocationDegrees)[trail.latitude doubleValue];
coordinate.longitude = (CLLocationDegrees)[trail.longitude doubleValue];
MKPlacemark *endLocation = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
MKMapItem *endingItem = [[MKMapItem alloc] initWithPlacemark:endLocation];
NSMutableDictionary *launchOptions = [NSMutableDictionary new];
[launchOptions setObject:MKLaunchOptionsDirectionsModeDriving forKey:MKLaunchOptionsDirectionsModeKey];
[endingItem openInMapsWithLaunchOptions:launchOptions];
}
MKPlacemark *endLocation = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
MKMapItem *endingItem = [[MKMapItem alloc] initWithPlacemark:endLocation];
NSMutableDictionary *launchOptions = [NSMutableDictionary new];
[launchOptions setObject:MKLaunchOptionsDirectionsModeDriving forKey:MKLaunchOptionsDirectionsModeKey];
[endingItem openInMapsWithLaunchOptions:launchOptions];
}
当我在控制台中打印出coordinate.latitude以查看其值时,我得到0并且对于coordinate.longitude:1。这些不是来自API的值。我是从API准确地获取其他数据。为什么坐标数不正确?
答案 0 :(得分:0)
您是否尝试将两个属性声明为强? 实际上NSNumber是一个指针!
尝试:
@property (nonatomic, strong) NSNumber *latitude;
@property (nonatomic, strong) NSNumber *longitude;
而不是:
@property (nonatomic, assign) NSNumber *latitude;
@property (nonatomic, assign) NSNumber *longitude;
说实话,在我看来,将两个属性定义为double或CLLocationDegrees(实际上是typedef double CLLocationDegrees;)
更好@property (nonatomic, assign) double latitude;
@property (nonatomic, assign) double longitude;
或以更“紧凑”的方式:
@property (nonatomic,assign)CLLocationCoordinate2D coordinate;