我正在查看以下有关问题的讨论,以尝试了解如何从plist读取位置并相应地将图视图固定到别针:
MapKit based app crashing when loading from plist
我在了解如何进行这项工作时遇到问题。如果我在注释中进行硬编码,那么我可以使其正常工作,这样我就不明白我要去哪里出错了。我认为这可能是我访问.plst中数据的方式。我的列表具有以下结构:
<array>
<dict>
<key>rowData</key>
<array>
<dict>
<key>details</key>
<string>Some minor info</string>
<key>latitude</key>
<strong>53.958756</string>
<key>Location</key>
<string>Location One</string>
<key>lontitude</key>
<string>-1.07937</string>
</dict>
</array>
</dict>
</array>
我尝试使用上述问题的答案中的代码访问此数据,但并不高兴:
-(id)initWithDictionary:(NSDictionary *)dict{
self = [super init];
if(self!=nil){
coordinate.latitude = [[dict objectForKey:@"latitude"] doubleValue];
coordinate.longitude = [[dict objectForKey:@"longitude"] doubleValue];
self.title = [dict objectForKey:@"Location"];
self.subtitle = [dict objectForKey:@"details"];
}
return self;
我的viewDidLoad看起来也与上面提到的其他问题有些不同。看起来像这样:
- (void)gotoLocation
{
// set location as York, UK
MKCoordinateRegion newRegion;
newRegion.center.latitude = 53.960025;
newRegion.center.longitude = -1.082697;
newRegion.span.latitudeDelta = 0.0012872;
newRegion.span.longitudeDelta = 0.0159863;
[self.map setRegion:newRegion animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//Set up map
self.map.mapType = MKMapTypeStandard; // also MKMapTypeSatellite or MKMapTypeHybrid
[self gotoLocation];
// Get the the plist in application bundle
NSString *path = [[NSBundle mainBundle] pathForResource:@"Places" ofType:@"plist"];
// Retrieve the plists root element array
NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(@"Grabbed locations.plist ok");
if (array) {
NSMutableDictionary* myDict = [NSMutableDictionary dictionaryWithCapacity:[array count]];
for (NSDictionary* dict in array) {
MapAnnotations* annotation = [[MapAnnotations alloc]initWithDictionary:dict];
[self.map addAnnotation:annotation];
[annotation release];
}
NSLog(@"The count: %i", [myDict count]);
}
else {
NSLog(@"Plist does not exist");
}
}
如果有人可以向我解释我要去哪里哪里以及如何做我需要做的事情,我将不胜感激。
谢谢阅读。
最佳答案
首先,plist有两个问题(至少与您问题中的示例有关):<strong>
(在latitude
键下)应为<string>
lontitude
应该是longitude
接下来,您的plist结构是一个数组,其中包含一个带有一个键“ rowData”的字典,其值是字典数组。但是代码循环遍历array
变量,该变量仅包含最外面的数组(该数组仅包含带有“ rowData”键的单个字典)。因此,在initWithDictionary
中,objectForKey
都返回nil,因为与位置相关的键不在最外面的字典中。
您想重新构造plist,使其仅是位置词典的数组(消除“ rowData”字典),或者更新代码以将数组放入“ rowData”键中并循环遍历:
NSArray *rowDataArray = [[array objectAtIndex:0] objectForKey:@"rowData"];
for (NSDictionary* dict in rowDataArray) //instead of "in array"
最后,
myDict
字典并没有真正使用。其计数的NSLog将始终显示为零,因为dictionaryWithCapacity
行仅分配内存,但不添加任何对象。我看不到需要myDict
变量-我将其删除。关于ios - 映射Xcode中plist的标注?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6823422/