将Array、Dictionary等集合类的序列化和反序列化
by Elton on 二.15, 2010, under iPhone
Objective-C的集合类序列化到文件中或者从文件中反序列化其实很简单,请看下面的示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | NSArray *array = [NSArray arrayWithObjects: @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: array, @"array", @"Stout", @"dark", @"Hefeweizen", @"wheat", @"IPA", @"hoppy", nil]; // 得到documents directory的路径 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); if ([paths count] > 0) { // Array的保存路径 NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"array.out"]; // dictionary的保存路径 NSString *dictPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"dict.out"]; // 保存array [array writeToFile:arrayPath atomically:YES]; // 保存dictionary [dictionary writeToFile:dictPath atomically:YES]; // 从文件中读取回来 NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath]; NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile:dictPath]; for (NSString *element in arrayFromFile) NSLog(@"Beer: %@", element); for (NSString *key in dictFromFile) NSLog(@"%@ Style: %@", key, [dictionary valueForKey:key]); } |
输出如下:




七月 19th, 2010 on 17:13
字典是反序的。。。
八月 15th, 2010 on 18:56
A genuinely great article by you my pal. We have bookmarked this web page and can appear again following several days to verify for just about any new posts that you just make.
八月 16th, 2010 on 03:40
Awesome article which has obtained me considering concerning the prospective of the idea. Definitely actually awesome.
九月 6th, 2010 on 08:06
Hello. I just did some web surfing and discovered this blog site. I went by way of this blog site put up and it is truly wonderful.I genuinely actually appreciate your web site.Completely, the part of writing is in confidence the extremely finest on this genuinely value even though subject. I added it and i’m searching forward for your upcoming website blogposts. I also seen that your website has some fantastic leading carried out to it. I will right away consider maintain of your rss feed to remain knowledgeable of any changes. Amazing info you obtained right here.If possible keep replace on your excellent submit.Many thanks.
十月 16th, 2010 on 09:28
Great blog! I genuinely love how it’s easy on my eyes as well as the info are well written. I am wondering how I can be notified whenever a new post has been made. I have subscribed to your rss feed which need to do the trick! Have a nice day!
十月 22nd, 2010 on 02:29
I love the way you write and also the theme on your blog. Did you code this yourself or was it done by a professional? I’m very very impressed.