2011-10-03 47 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