无法读取plist文件

时间:2013-12-16 14:08:43

标签: ios objective-c plist

我在plist文件中读取数据时遇到问题。我没有像我期待的那样在控制台中打印出titleString。我做错了什么?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);
    }

1 个答案:

答案 0 :(得分:2)

您的主要元素(Root)是Dictionary - 而不是Array - 通过单击旁边的类型在plist中更改它。

您的代码中也存在问题 - 您永远不会按名称访问“Root”元素 - 它是默认的顶级对象。考虑进行额外的阵列初始化,这不是必需的。

固定代码:

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