iOS开发 数据存储之write

来源:互联网 发布:贵阳网站建设方舟网络 编辑:程序博客网 时间:2024/06/14 01:00

write写入方式:永久保存在磁盘中

1.获得文件保存的路劲

//使用C函数NSSearchPathForDirectoriesInDomains来获得沙盒中目录的全路径.该函数有三个参数,目录类型、he domain mask、布尔值.其中布尔值表示是否需要通过~扩展路径.而且第一个参数是不变的,即为NSSearchPathDirectory.在iOS中后两个参数也是不变的,即为:NSUserDomainMask 和 YESNSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);

2.生成在该路劲下的文件

//writePath 是保存文件的文件名NSString *documentPath = [documentPaths[0] stringByAppendingPathComponent:writePath];

3.往文件中写入数据

NSString,NSArray,NSDictionary,NSData都有方法writeToFile:atomically:

//将NSData类型对象data写入文件,文件名为writePath[data writeToFile:documentPath atomically:YES];

4.从文件中读取数据

//从documentPath中读取出数据NSData *data = [NSData dataWithContentsOfFile:documentPath];

5.从文件中删除数据

[[NSFileManager defaultManager] removeItemAtPath:documentPath error:nil];

阅读全文
0 0