2011-10-03 54 views
0

我有一个包含三个元素的数组的plist,所有这些都是字典。这些字典每个包含四项(纬度,经度,标题,副标题)。我想遍历每个元素并获取纬度和经度(这两者都是字典的属性)。通过包含字典数组的plist循环

使用以下代码。

- (void)loadAnnotations{ 

    //retrieve path of plist file and populate relevant types with its information 
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Places1" ofType:@"plist"]; 
    branchList = [[NSArray alloc] initWithContentsOfFile:plistPath]; 

    NSLog(@"hi inside method",branchList.lastObject); 

    self.branchList =[NSMutableArray array]; 
    //code ok until this 
    for (NSDictionary *key in branchList) 
{ NSLog(@"hi in loop"); 

     PlaceFinderAnnotation *placeAnnotations = [[PlaceFinderAnnotation alloc] init]; 
     //loop through annotations array, creating parking annotations filled with the information found in the plist 

      CLLocationDegrees latitude = [[key valueForKey:@"latitude"]floatValue]; 
      CLLocationDegrees longitude = [[key valueForKey:@"longitude"]floatValue]; 
      placeAnnotations.coordinate = CLLocationCoordinate2DMake(latitude, longitude); 

      [self.branchList addObject:placeAnnotations]; 
      [placeAnnotations release]; placeAnnotations= nil; 
      objectForKey:@"subtitle"]]; 

     } 
    } 

问题是它没有进入循环。这意味着它不会打印出log命令“hi looppp”。

+0

如果这是你的整个代码,那肯定是坏了。如果这不是你的整个代码,那么你不会因为遗漏部分而对自己有利。 –

回答

2

假设这段代码成功(我们必须假设,因为你似乎没有被检查,以确保)。让我们假设(因为你不说)“branchList”是当前类的一个实例变量:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Places1" ofType:@"plist"]; 
branchList = [[NSArray alloc] initWithContentsOfFile:plistPath]; 

此希望你留下一个数组。你当然可以通过检查以确保它留下一个数组(if (branchList)...)来消除“希望”。然后,因为“branchList”似乎是一个实例变量,你马上吹去用一个空数组替换它(使用访问,而不是直接将其设置为上面一样):

self.branchList =[NSMutableArray array]; 

...所以你试着迭代一个空循环(所以NSLog()语句永远不会执行)。

0
self.branchList =[NSMutableArray array]; 

创建一个空数组,这就是for语句被要求循环的东西。

删除该语句。

也许这就是你想要什么:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Places1" ofType:@"plist"]; 
self.branchList = [NSArray arrayWithContentsOfFile:plistPath]; 
NSLog(@"hi inside method",branchList.lastObject); 

for (NSDictionary *key in self.branchList) { 
    NSLog(@"hi inside loopppp"); 
-1
if([branchlist count]){ 
    for (NSDictionary *key in self.branchList) { 
      NSLog(@"Key item in branchlist %@",key); 
    } 
}else{ 
    NSLog(@"There is no items in branchlist"); 
} 
+1

有趣的是,if语句更复杂一些,只需使用:if([branchlist count])'。如果'branchlist'为零'[branchlist count]'将返回0. – zaph

+0

糟糕。赶时间,我忘了完成条件。我已将我的答案[分支列表计数]修改为[分支列表计数]> 0。所以如果该列表有多于0个元素,那么它应该迭代。 –

+0

仍然只需要:'if([branchlist count])'在Obj-C发送消息给nil是允许的并且已经定义了行为。 – zaph