【问题标题】:read from .plist file从 .plist 文件中读取
【发布时间】:2014-03-28 20:18:22
【问题描述】:

出了点小问题。我有一个 .plist 文件,其中包含下一个数据

所以我无法理解,我需要如何读取第一个数组,而不是数组读取字典。或者可能需要重写文件并更改 Root 键以键入字典,并像这样读取:

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

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    可以通过以下代码实现:

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

    这个数组将包含所有的字典,你可以像这样获取它们:

    NSDictionary *dict = [dataArray objectAtIndex:0];
    

    【讨论】:

    • 除此之外,如果文件存在,则会抛出从 Documents 文件夹加载文件的代码。
    • 它实际上并没有回答这个问题。问题是关于从数组中获取所需的数据。
    • objectAtIndex: 是旧语法,有一些更新
    • @IgorMatyushkin:dataArray[0],我喜欢旧语法(不知道为什么:P)
    【解决方案2】:
    SString *plistFile = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:plistFile];
    
    for(NSDictionary *dictionary in array) {
        NSLog(@"%@", dictionary);
    }
    
    NSDictionary *item0 = array[0];
    NSString *imageName = item[0][@"name"];
    

    【讨论】:

    • 这会抛出从 Documents 文件夹中加载文件的代码(如果存在)。 OP 可能仍然想要该代码。
    • OP 的代码首先在 Documents 文件夹中查找,然后使用资源包作为后备。为了 OP 的缘故,我指出这个答案消除了这种逻辑。
    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多