How to find programmatically what is the root element of the plist
How to find out programmatically what's the root element of the p开发者_开发问答list, i.e whether it is Array or Dictionary?
Load the plist with +[NSPropertyListSerialization propertyListFromData:…]
, then check the -class
of the resulting object.
Try the below:
NSData *plistData;
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
plistData = [NSData dataWithContentsOfFile:localizedPath];
plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if([plist isKindOfClass:[NSDictionary class]]){
//do some ...
}
if([plist isKindOfClass:[NSArray class]]){
//do some ...
}
Additional reading from Apple.
Here’s the Core Foundation way:
if (CFGetTypeID((CFPropertyListRef)myPropertyList) == CFDictionaryGetTypeID()) {
// its a dictionary
}
You should not use the class method for this. Use NSObject's isKindOfClass: (or isMemberOfClass:) to test if the object's class is [NSArray class] or [NSDictionary class].
see: +[NSObject class]
精彩评论