沙盒操作

沙盒操作

1.沙盒说明
  • Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
  • tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
  • Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除
  • iTunes在与iPhone同步时,备份所有的Documents和Library文,iPhone在重启时,会丢弃所有的tmp文件。
2.沙盒读写操作

  • directory : NSSearchPathDirectory类型的enum值,表明我们要搜索的目录名称,比如这里用NSDocumentDirectory表明我们要搜索的是Documents目录。如果我们将其换成NSCachesDirectory就表示我们搜索的是Library/Caches目录。
  • domainMask: NSSearchPathDomainMask类型的enum值,指定搜索范围,这里的NSUserDomainMask表示搜索的范围限制于当前应用的沙盒目录。还可以写成NSLocalDomainMask(表示/Library)、NSNetworkDomainMask(表示/Network)等。
  • expandTilde: BOOL值,表示是否展开波浪线~。我们知道在iOS中~的全写形式是/User/userName,该值为YES即表示写成全写形式,为NO就表示直接写成“~”。
1.上诉图片获取
-(void) test{
    //沙盒目录
    NSLog(@"%@",NSHomeDirectory());
    //tep
    NSLog(@"%@",NSTemporaryDirectory());
    //Myapp.app
    NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
    //Documents
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"%@",path);

}
2.使用NSSearchPathForDirectoriesInDomains
//获得Library/Caches文件夹:NSCachesDirectory,还有其他
NSString *pathCache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//获得文件名
NSString *fileName=[app.icon lastPathComponent];
//获得文件全路径
NSString *file=[pathCache stringByAppendingPathComponent:fileName];
//加载沙盒中图片
NSData *dataWithFile=[NSData dataWithContentsOfFile:file];

NSLog(@"沙盒中找到");
image=[UIImage imageWithData:dataWithFile];
//           缓存中加入图片
self.imageCache[path]=image;

NSLog(@"下载");
NSURL *url=[NSURL URLWithString:path];
NSData *dataWithUrl=[NSData dataWithContentsOfURL:url];
image=[UIImage imageWithData:dataWithUrl];
//          缓存与沙盒中加入图片
self.imageCache[path]=image;
[dataWithUrl writeToFile:file atomically:YES];

3.NSUserDefaults使用
  • 对于应用来说,每个用户都有自己的独特偏好设置,而好的应用会让用户根据喜好选择合适的使用方式,把这些偏好记录在应用包的plist文件中,通过NSUserDefaults类来访问,这是NSUserDefaults的常用姿势。
  • 位置Library
    NSString *key=@"CFBundleShortVersionString";

    NSString *currentVersion=[NSBundle mainBundle].infoDictionary[key];
    //读(通过类方法standardUserDefaults可以获取NSUserDefaults单例)
    NSString *sanboxVersion=[[NSUserDefaults standardUserDefaults] stringForKey:key];
    //写
    [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];
    //方法synchronise是为了强制存储,其实并非必要
    [[NSUserDefaults standardUserDefaults]synchronize];

转载于:https://my.oschina.net/HYLApple/blog/743126

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值