How can I convert NSDictionary to NSData and vice versa?

来源:互联网 发布:linux中的grep命令 编辑:程序博客网 时间:2024/06/05 20:27

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.
0 0
原创粉丝点击