简体   繁体   English

plist文件中的NSArray或NSDictionary

[英]NSArray or NSDictionary from plist file

In a method I need to read a NSArray or NSDictionary from a plist file. 在一种方法中,我需要从plist文件读取NSArrayNSDictionary

Here is my problem : How can I create a NSArray OR a NSDictionary from a plist file when I don't know if it's an array or dictionary in it ? 这是我的问题:不知道其中是数组还是字典时,如何从plist文件创建NSArrayNSDictionary

I know I can make : 我知道我可以做到:

NSArray *myArray = [NSArray arrayWithContentsOfFile:filePath];

or 要么

NSDictionary *myDico = [NSDictionary dictionaryWithContentsOfFile:filePath];

But I don't know if filePath contains a NSArray or a NSDictionary . 但是我不知道filePath是否包含NSArrayNSDictionary I would like something like : 我想要类似的东西:

id myObject = [... ...WithContentOfFile:filePath];

Can somebody help me and give me the best way to do this ? 有人可以帮助我,给我最好的方法吗?

Here's how 这是如何做

NSData *data = [NSData dataWithContentsOfFile:filePath];
id obj = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:nil];

if([obj isKindOfClass:[NSDictionary class]]) {
    //cast obj to NSDictionary
}
else if([obj isKindOfClass:[NSArray class]]) {
    //cast obj to NSArray
}

You can use isKindOfClass method to detect which class is that. 您可以使用isKindOfClass方法检测该类。 You will have to load .plist file using: 您将必须使用以下方式加载.plist文件:

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];
id objectFromPlist = [NSPropertyListSerialization
   propertyListWithData:plistXML
   options:0
   format:&format
   errorDescription:&errorDesc];

And you can check here: 您可以在这里查看:

if([objectFromPlist isKindOfClass:[NSArray class]])
{
    NSArray* plistArray = (NSArray*) classFromPlist;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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