[ios]从.plist 文件中读取

标签: ios Objective-C
发布时间: 2015/3/15 6:50:07
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

有一个小问题。我有一个.plist 文件,其中包含下一数据http://imageshack.com/a/img856/1421/xvzm.png

所以我不明白,怎么还要比读第一个数组,数组读取词典中。或也许需要重写文件和更改根键类型字典和读像这样:

NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
   NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
    plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
    propertyListFromData:plistXML
    mutabilityOption:NSPropertyListMutableContainersAndLeaves
    format:&format
    errorDescription:&errorDesc];
if (!temp) {
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}
self.personName = [temp objectForKey:@"Name"];
self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:@"Phones"]];

解决方法 1:

你可以通过下面的代码:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSArray  *dataArray = [NSArray arrayWithContentsOfFile:plistPath];

此数组将包含所有的词典,你可以让他们像:

NSDictionary *dict = [dataArray objectAtIndex:0];
赞助商