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

//文件夹里写入字符串
    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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值