Search code examples
iphoneobjective-ciosxcode4nsdictionary

Looping through a plist containing an array of dictionaries


I have a plist containing an array with three elements all of which are dictionaries. These dictionaries contain four items each (latitude, longitude, title, subtitle). I want to loop through each of the elements and get the latitude and longitude (both of which are attributes of the dictionary).

The following code is used.

    - (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"]];

        }
    }

The problem is it doesnt go into the loop. meaning it doesnt print out the log command "hi inside the looppp".


Solution

  • Let's assume this code succeeded (we have to assume because you don't appear to be checking to make sure). Let's also assume (because you don't say) "branchList" is an instance variable in the current class:

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

    This hopefully leaves you with an array. You could of course eliminate the "hopefully" by ... checking to make sure it leaves you with an array ( if (branchList)... ). Then, since "branchList" seems to be an instance variable, you immediately blow it away by replacing it with an empty array (using an accessor rather than setting it directly as you did above):

    self.branchList =[NSMutableArray array];
    

    ...so then you try to iterate an empty loop (so the NSLog() statement is never executed).