Search code examples
iosobjective-cplist

Can't Read plist File


I am having trouble reading the data in a plist file. I'm not getting the titleString printed in the console like I'm expecting. What am I doing wrong?enter image description here

NSString *path = [[NSBundle mainBundle] pathForResource:@"Events" ofType:@"plist"];
    NSDictionary *dictPri = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
    NSMutableArray *arrEvents = [[NSMutableArray alloc] initWithArray:[dictPri valueForKey:@"Root"]];

    for (NSDictionary *dict in arrEvents)
    {
        NSString *titleString = nil;
        NSString *date = nil;
        titleString = [NSString stringWithFormat:@"%@",[dict valueForKey:@"Title"]];
        date = [NSString stringWithFormat:@"%@",[dict valueForKey:@"Date"]];

        NSLog(@"Title String: %@", titleString);
    }

Solution

  • Your main element (Root) is Dictionary - not Array - change it in plist by clicking on type next to it.

    Also there is a problem in your code - you never access "Root" element by name - it's by default top-level object. Consider taking out additional array initialization which is not required.

    Fixed code:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Events" ofType:@"plist"];
    NSArray* arrEvents = [NSArray arrayWithContentsOfFile:path];
    
    for (NSDictionary *dict in arrEvents)
    {
        NSString *titleString = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Title"]];
        NSString *date = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Date"]];
    
        NSLog(@"Title String: %@", titleString);
    }