关闭

ios 数据持久化之沙盒

标签: ios沙盒
215人阅读 评论(0) 收藏 举报

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3232次
    • 积分:139
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档