Jonathan
Jonathan

Reputation: 742

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 ?

Upvotes: 1

Views: 757

Answers (2)

Grzegorz Krukowski
Grzegorz Krukowski

Reputation: 19792

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

Upvotes: 1

graver
graver

Reputation: 15213

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
}

Upvotes: 6

Related Questions