Reputation: 742
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
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
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