iOS数据持久化,写入,归档和反归档

来源:互联网 发布:sql给表中添加信息 编辑:程序博客网 时间:2024/05/10 02:34
//文件夹里写入字符串    NSString *guyu=@"宇";    NSString *guyustr=[newStr stringByAppendingPathComponent:@"guyu.txt"];    [guyu writeToFile:guyustr atomically:YES encoding:NSUTF8StringEncoding error:nil];    NSLog(@"%@",guyustr); ///把数组,字典写入到本地    NSArray *sandBox=@[@"1",@"2",@"3",@"4"];    //通过数组,,获取沙盒地址..    NSArray *sandBox1=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    //用字符串保存沙盒路径    NSString *documentPath=sandBox1[0];    //给要写入的文件拼接路径    NSString *documentPath1=[documentPath stringByAppendingPathComponent:@"sadfsdf.txt" ];    [sandBox writeToFile:documentPath1 atomically:YES];    NSLog(@"%@",documentPath1);    //把数组读出来    NSArray *temp=[NSArray arrayWithContentsOfFile:documentPath1];    NSLog(@"%@",temp);////通过文件管理者对文件夹进行操作    ///在document文件夹下创建一个新的文件夹    NSArray *sandArr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *sandStr=sandArr[0];    //创建一个文件管理者    NSFileManager *manager=[NSFileManager defaultManager];    //给要创建的文件夹拼接一个路径    NSString *newStr=[sandStr stringByAppendingPathComponent:@"宇"];    //文件的名字不需要任何扩展名    //通过manager进行文件夹的创建    [manager createDirectoryAtPath:newStr withIntermediateDirectories:YES attributes:nil error:nil];    NSLog(@"%@",newStr);//向新建的文件夹里写入字符串    NSString *guyu=@"宇";    NSString *guyustr=[newStr stringByAppendingPathComponent:@"guyu.txt”];    [guyu writeToFile:guyustr atomically:YES encoding:NSUTF8StringEncoding error:nil];    NSLog(@"%@",guyustr);    ///移除文件夹    [manager removeItemAtPath:guyustr error:nil];  ///移除cache清除缓存    NSArray *cacheArr=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    NSLog(@"%@",cacheArr);    NSString *cacheStr=cacheArr[0];    [manager removeItemAtPath:cacheStr error:nil];   Student *stu=[Student stuWithName:@"安逸臣" stuSex:@"男" stuAge:@"25" stuHobby:@"打球"];    //1.通过数组获取沙盒路径    NSArray *sandBox=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    //2.用字符串接受沙盒路径    NSString *sandPath=sandBox[0];    //3.拼接文件夹路径,这个文件的扩展名是任意的    NSString *documentPath=[sandPath stringByAppendingPathComponent:@"学生.avi"];    ///对对象进行归档操作    //第一个参数:要实施归档的对象    //第二个参数:路径    [NSKeyedArchiver archiveRootObject:stu toFile:documentPath];    NSLog(@"%@",documentPath);    //反归档    Student *newStu=[NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];    NSLog(@"%@",newStu.name);

0 0
原创粉丝点击