【发布时间】:2011-06-23 06:15:22
【问题描述】:
编辑:
抱歉,我发布问题时已经晚了,让我看看我是否可以更清楚地说明这一点。 目前我的应用程序没有编译错误并运行,但我期望它做的是放置 MKMapview 上的引脚。当我运行它时,地图上没有显示任何图钉。当我调查控制台时,没有显示错误或指示。我缩小了错误范围 到这两行:
NSString* lng_coord = [[dict objectForKey:key] description];
[CelebsAnnotation setLongitude:[lng_coord doubleValue]];
问题是我似乎无法让 lng_coord doubleValue 给我一个双精度值,因为如果是这样,那么引脚就会出现。我知道这一点,因为如果我这样做:
[CelebsAnnotation setLongitude:54.39281]; // for example
然后图钉出现在地图上。所以如果 lng_coord 没有给我一个 doubleValue,那 我认为它一定不是 NSString,这意味着 objectForKey 没有返回 NSString(尽管我有充分的理由相信这是因为我使用了):
// Use when fetching text data
NSString *response = [request responseString];
然后使用 SBJSON 解析该响应字符串。我知道我成功地从我的 JSON 响应中解析了 lng / lat 值,因为我可以这样做:
NSLog(@"%@", lng_coord);
它会在控制台中打印出正确的数值。我试过像这样从 objectForKey 转换返回值:
NSString* lng_coord = (NSString*)[dict objectForKey:key];
没有成功。然后我在 SO 周围搜索了一种将 objectForKey 的返回值转换为 NSString 的方法,并且“描述”似乎是答案,尽管 也没有为我工作。
SO.. 总而言之,我需要一个 lng_coord 的 NSString 值,以便我可以获得该字符串的 doubleValue!谢谢大家的时间。只爱 Stack Overflow。
这是我的 PHP 脚本中的 JSON 编码响应,正在由我的应用程序解析:
[
{"lng":"49.2796758","lat":"-123.1365125"},
{"lng":"49.2695877","lat":"-123.0443507"},
{"lng":"50.4547222","lat":"-104.6066667"},
{"lng":"49.2696243","lat":"-123.0696036"},
{"lng":"49.2688942","lat":"-123.1388003"},
{"lng":"49.2796758","lat":"-123.1365125"}
]
这是包含我上面描述的错误的函数:
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *response = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *pins = [parser objectWithString:response error:nil]; // an array of dictionaries that contain coords
// loop through the pins array of dictionaries (lng, lat)
for (int i = 0; i < [pins count]; i++)
{
NSDictionary *dict = [pins objectAtIndex:i];
for(NSString *key in dict) {
if ([key isEqualToString: @"lng"]) { // access of the longitude coord
NSString* lng_coord = [[dict objectForKey:key] description];
[CelebsAnnotation setLongitude:[lng_coord doubleValue]];
}
if ([key isEqualToString:@"lat"]) { // access of the latitude coord
NSString* lat_coord = [[dict objectForKey:key] description];
[CelebsAnnotation setLatitude:[lat_coord doubleValue]];
}
}
// now that you've set the lng/lat, insert the annotation at index i
CelebsAnnotation *newAnnotation = [[CelebsAnnotation alloc] init]; // template object for all pins
[self.mapAnnotations insertObject:newAnnotation atIndex:i];
[newAnnotation release];
[self.mapView removeAnnotations:self.mapView.annotations];
[self.mapView addAnnotation:[self.mapAnnotations objectAtIndex:i]]; // add annotation
}
【问题讨论】:
-
目前还不清楚到底出了什么问题。你的应用程序崩溃了吗?你是 0 吗?
-
试试这个 -
NSLog(@"%@", NSStringFromClass([[dict objectForKey:key] class])); -
我已经编辑了这个问题,以便更清楚地说明我在问什么。还有其他想法吗?
标签: objective-c json nsdata