简体   繁体   中英

How to determine if plist contains NSDictionary or NSMutableArray?

I may be phrasing the question incorrectly based on my situation - sorry if that's the case.

Here's the issue: In a previous version of my app, I'm saving an NSMutableArray to a plist using NSCoding.

In a new version, I've added settings data, so I now put the previous array and the new data in an NSDictionary then use NSCoding. Works fine.

However, for this release, I'll have to determine if an existing plist is the old version (NSMutableArray) or the new one (NSDictionary).

The basic code is this:

NSData *codedData=[[NSData alloc] initWithContentsOfFile:plistPath];
//EITHER this (array):    allMsgs=[NSKeyedUnarchiver unarchiveObjectWithData:codedData];
//OR this (nsdict):       tmpdict=(NSDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:codedData];

How can I read the plist and determine if it's an NSDictionary or NSMutableArray without throwing errors?

Just store the unarchived object as an id , then use isKindOfClass: to check its class:

id unarchivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:codedData];
if ([unarchivedObject isKindOfClass:[NSArray class]]) {
    // do something
} else if ([unarchivedObject isKindOfClass:[NSDictionary class]]) {
    // do something else
}

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