简体   繁体   中英

NSArray or NSDictionary from plist file

In a method I need to read a NSArray or NSDictionary from a plist file.

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 ?

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 . 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. You will have to load .plist file using:

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

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