A little category to get an NSDictionary from an NSString containing a plist
Posted: | Author: Jörn | Filed under: iOS, Objective-C | Tags: NSDictionary, parsing, plist | 2 Comments »I really like the plist format. Being able to transform a plist file into a NSDictionary with one line of code really appeals to the lazy guy in me. So when our backend developer asked me what my preferred format for server responses would be, I told him to send his responses in plist format. That’s when I came across a little problem: When accessing the response body of the request, all I got was a NSString. The string contained the plist, but it was still a string and not the usual XML structure that you normally get when you open a plist file.
I found a way to parse a NSString into a NSDictionary on StackOverflow (thanks to Peter N Lewis for his answer).
So I decided to write a little category to extend NSDictionary so that it can initialize a NSDictionary with a plist NSString:
@interface NSDictionary (DictionaryWithString)
+ (NSDictionary *)dictionaryWithString:(NSString *)string;
@end
#import "NSDictionary+DictionaryWithString.h"
@implementation NSDictionary (DictionaryWithString)
+ (NSDictionary *)dictionaryWithString:(NSString *)string {
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *error;
NSPropertyListFormat format;
NSDictionary *dict = [NSPropertyListSerialization
propertyListFromData:data
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if(!dict){
NSLog(@"ERROR: could not parse NSString: %@",error);
[error release];
}
return dict;
}
@end
Feel free to use it in your own projects.