您的位置:首页 > 移动开发 > IOS开发

ios 数据持久化之沙盒

2014-11-29 17:46 232 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: