TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
楼主 |
发表于 2014-1-21 21:41:01
|
显示全部楼层
本帖最后由 Sian 于 2014-1-21 21:44 编辑
使用NSData进行文件归档操作,可保存不同类型的数据
1、创建一个String类、Array类、Dictionary类,并初始化赋值,存储到Data中,写入文件;
2、从文件中读取数据;
main.m- //
- // main.m
- // Archiver
- //
- // Created by yusian on 14-1-20.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #define PATH @"/tmp/file.plist"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
- NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"One", @"1", @"Two", @"2", @"Three", @"3", nil];
- NSArray * array = [[NSArray alloc] initWithObjects:@"One", @"Two", nil];
- NSString * str = [[NSString alloc] initWithString:@"This is a TestString"];
- NSMutableData * data = [[NSMutableData alloc] init];
- NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
-
- [archiver encodeObject:dict forKey:@"dict"];
- [archiver encodeObject:array forKey:@"array"];
- [archiver encodeObject:str forKey:@"str"];
- [archiver finishEncoding];
-
- [data writeToFile:PATH atomically:YES];
-
- [archiver release];
- [data release];
- [str release];
- [array release];
-
- }
- return 0;
- }
复制代码 运行结果即在/tmp生成file.plist文件,该文件用文本编辑器无法直接打开,但可以用xcode读取,如图所示:
|
|