How can I convert NSDictionary to NSData and vice versa?

http://stackoverflow.com/questions/5513075/how-can-i-convert-nsdictionary-to-nsdata-and-vice-versa

NSDictionary -> NSData:

    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
    [archiver finishEncoding];
    [archiver release];

    // Here, data holds the serialized version of your dictionary
    // do what you need to do with it before you:
    [data release];
NSData -> NSDictionary

    NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
    [unarchiver finishDecoding];
    [unarchiver release];
    [data release];
You can do that with any class that conforms to NSCoding.

你可能感兴趣的:(How can I convert NSDictionary to NSData and vice versa?)