簡體   English   中英

遍歷包含字典數組的plist

[英]Looping through a plist containing an array of dictionaries

我有一個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"]];

        }
    }

問題是它不會進入循環。 這意味着它不會打印出日志命令“ hipp the looppp”。

讓我們假設這段代碼成功了(我們不得不假設,因為您似乎沒有進行檢查來確保這一點)。 我們還假設(因為您不說)“ branchList”是當前類中的一個實例變量:

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

希望這會給您留下一個數組。 您當然可以通過...檢查以確保它為您留下了一個數組( if (branchList)... )來消除“希望”。 然后,由於“ branchList”似乎是一個實例變量,因此您可以通過將其替換為空數組(使用訪問器而不是像上面那樣直接設置它)立即將其吹走:

self.branchList =[NSMutableArray array];

...因此,您嘗試迭代一個空循環(這樣就永遠不會執行NSLog()語句)。

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");
if([branchlist count]){
    for (NSDictionary *key in self.branchList) {
           NSLog(@"Key item in branchlist %@",key);
    }
}else{
     NSLog(@"There is no items in branchlist");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM