数据持久化 属性列表代码

- (void)viewDidLoad {安全

    [super viewDidLoad];ide

    self.view.backgroundColor=[UIColor lightGrayColor];函数

//    建立字符串持久化按钮atom

    

    self.buttonString=[[UIButton alloc]initWithFrame:CGRectMake(100, 50, 200, 50)];spa

    [self.buttonString setTitle:@"字符串持久化" forState:UIControlStateNormal];orm

    self.buttonString.backgroundColor=[UIColor greenColor];对象

//    方法调用字符串

    [self.buttonString addTarget:self action:@selector(dataPersistence) forControlEvents:UIControlEventTouchUpInside];get

    [self.view addSubview:self.buttonString];string

 

}

 

//数据持久化

-(void)dataPersistence

{

//    字符串持久化

 

    //获取Documents文件目录:常量NSDocumentDirectory代表咱们正在查找Documents目录的路径。第二个常量NSUserDomainMask代表咱们但愿将搜索限制在应用的沙盒内,在OS X中代表咱们但愿该函数查看用户的主目录。

    NSArray *arrayStr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    //表示将文件放入Documents文件的最后一个,即path做为最后一个对象

    NSString *path=[arrayStr lastObject];

    //@"ANewFile.plist"为新文件名,方法调用后 ,newPathStr 中存放了文件 ANewFile.plist 在 Documents 目录中的完整路径

    NSString *newPathStr=[path stringByAppendingPathComponent:@"ANewFile.plist"];

    NSLog(@"%@",newPathStr);

    //先建立一个NSString(字符串)类型的对象,而后调用实例方法 writeToFile:atomically 将参数写入文件中

    NSString *myFile=@"NewString";

    [myFile writeToFile:newPathStr atomically:YES encoding:NSUTF8StringEncoding error:nil];

//    说明:这里的atomically参数让该方法将数据写入辅助文件,而不是写入指定位置。成功写入该文件以后,辅助文件将被复制到第一个参数指定的位置。这是更安全的写入文件的方法,由于若是应用在保存期间崩溃,则现有文件(若是有)不会被破坏。尽管增长一点开销,可是多数状况下仍是值得的。

 

 

//    说明:这里的myFile 是字符串,因此是字符串的持久化,他能够用Array,Dictionary,Data等能够被序列化的类型;能够被序列化的类型有:

1)NSArray、NSMutableArray

2)NSDictionary、NSMutableDictionary

3)NSData、NSMutableData

4)NSString、NSMutableString

5)NSNumber

6)NSDate

 

//获取几种沙盒目录的方法

     //获取Documents目录

       NSArray *arrayStr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

       NSString *path=[arrayStr lastObject];

 

    //获取Library目录方法

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *libraryDirectory = paths[0];

 

    //获取tmp目录方法    

    NSString *tempPath = NSTemporaryDirectory();

    NSString *filename = [tempPath stringByAppendingPathComponent:@"theFile.txt"];

}

相关文章
相关标签/搜索