简体   繁体   中英

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? 在此输入图像描述

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);
    }

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM