ios 数据持久化之沙盒

1,访问沙盒路径

    //1,home主目录里面有,Documents,Library,tmp和一个应用程序
    NSLog(@"Home:%@",NSHomeDirectory());
    //2,Documents
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@",documentsPath);
    //3,Library
    NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@",libraryPath);
    //4,tmp
    NSLog(@"tmp:%@",NSTemporaryDirectory());
    //5,caches
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@",cachesPath);
    //6,user
    NSString *user = NSUserName();
    NSLog(@"user:%@",user);
    
    //7,NSBundle:图片路径
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"];
    NSLog(@"bundle:%@",bundle);

2,简单文件写入

//1,获取文件路径
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@",documentsPath);
    //2,拼接文件路径
    NSString *file = [documentsPath stringByAppendingString:@"/myText.txt"];
    //3,准备写入的内容
    NSString *content = @"Hello World!";
    
    //4,写入(下面yes是原子性,整个写入,no有多少写多少)
    [content writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    //读取
    NSString *readString = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",readString);
3,

 //NSArray
    //1,获取document路径
    //2,拼接文件路径
    NSString *arrayPath = [documentsPath stringByAppendingString:@"/array.plist"];
    //3,准备内容
    NSArray *array = @[@"123",@"456",@"789"];
    //4,写入
    [array writeToFile:arrayPath atomically:YES];
    
    //5,读取
    NSArray *readArray = [NSArray arrayWithContentsOfFile:arrayPath];
    NSLog(@"%@",readArray);
    
    //NSDictionary
    //1,获取文件路径
    //2,拼接文件路径
    NSString *dictPath = [documentsPath stringByAppendingString:@"/dict.plist"];
    //3,准备写入的内容
    NSDictionary *dict = @{@"name": @"张强",@"age":@"21"};
    //4,写入内容
    [dict writeToFile:dictPath atomically:YES];
    //5,读取
    NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:dictPath];
    NSLog(@"%@",readDict);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值