码迷,mamicode.com
首页 > 编程语言 > 详细

字符串,字典,数组写入本地文件和从本地文件读取

时间:2016-02-09 17:25:08      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:

 

一.字符串,字典,数组存储到本地文件
 字符串,数组,字典存储到本地文件过程一样,只是要存储的数据类型不同而已,这里以字符串存储到本地文件为例,如下:
    NSString *content = @"将字符串存储到本地文件";
    (1)获取Documents文件夹路径

     参数:(1)指定文件夹,(2)设置查找域,(3)是否使用详细路径    

   NSString *documentsPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES) firstObject];

    (2)拼接上要存储的文件路径(前面自动加上/),如果没有此文件系统会自动创建一个    

NSString *newFielPath = [documentsPath stringByAppendingPathComponent:@"aa.txt”];

    (3)将内容存储到指定文件路径    

NSError *error = nil;    

字符串写入本地文件参数:(1)要存储内容的文件路径,(2)是否使用原子特性,(3)存储格式  

   BOOL isSucceed = [contentwriteToFile:newFielPath atomically:YESencoding:NSUTF8StringEncoding  error:&error];



二.字符串,字典,数组,从本地文件读取
字符串,字典,数组从本地文件读取的过程一样,只是要读取的数据类型不同而已,这里以从本地文件读取字符串为例,如下

 NSError *error = nil;(最后也可以&error)    

   NSString *content = [NSString stringWithContentsOfFile:newFielPath encoding:NSUTF8StringEncoding error:nil]



三.总结

文件读写暂时只支持,NSString,NSArray,NSDictionary,NSData以及他们的子类 

写入文件方法:writeToFile:对象调用方法

读取文件:每个类自带的能够根据文件路径读取文件的方法:[类名 + WithContentOfFile],如下 

 NSString :[NSString StringWithContentOfFile:]

 NSArry :[NSArry arrayWithContentOfFiel:]
 NSDictionary :[NSDictionary dictionaryWithOfContentFile:]
 二进制流:[NSData dataWithOfContentFiel:] 对于NSArray,NSDictionary ,这种容器,内部成员也必须是能够实现文件读写的八个类之一

 

字符串,字典,数组写入本地文件和从本地文件读取

标签:

原文地址:http://www.cnblogs.com/qq411715078/p/5185612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!