iOS开发-进阶:沙盒操作与机制

本文介绍了iOS沙盒机制的设计目的及实现原理,详细解释了如何在iOS应用中操作沙盒,包括获取不同目录路径、创建文件夹与文件、读写文件等,并提供了具体的代码示例。

iOS 为什么要设计沙盒? 从 apple 官方文档来看, 沙盒把每一个 App 对数据和系统资源的调用封在 App 沙盒的内部, 这样每个 App 在操作数据与调用系统资源时都是独立的.


iOS 应用内如何操作沙盒? 在安装 App 时会创建很多容器, 其中每个容器都有不同的使用规则. Bundle 容器包括 App Bundle. 数据容器 (即沙盒, 下文用沙盒代替) 包括 App 与用户的数据. 沙盒容器被分为一些文件夹. 同时应用还可以接入额外的容器, 比如 iCloud 容器 (在需要时).



沙盒内的目录:



App 的数据应该如何存放在沙盒内?

下面让我们看一下沙盒操作的代码: 摘自:http://blog.youkuaiyun.com/xyz_lmn/article/details/8968213

1. 获取沙盒根目录:

-(void)dirHome{  
    NSString *dirHome=NSHomeDirectory();      
    NSLog(@"app_home: %@",dirHome);  
}  
2. 获取 Documents 目录路径:

//获取Documents目录  
-(NSString *)dirDoc{  
    //[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsDirectory = [paths objectAtIndex:0];  
    NSLog(@"app_home_doc: %@",documentsDirectory);  
    return documentsDirectory;  
}  
3. 获取 Library 目录路径

//获取Library目录  
-(void)dirLib{  
    //[NSHomeDirectory() stringByAppendingPathComponent:@"Library"];  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);  
    NSString *libraryDirectory = [paths objectAtIndex:0];  
    NSLog(@"app_home_lib: %@",libraryDirectory);  
}  
4. 获取 Cache 目录路径

//获取Cache目录  
-(void)dirCache{  
    NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
    NSString *cachePath = [cacPath objectAtIndex:0];  
    NSLog(@"app_home_lib_cache: %@",cachePath);  
}  
5. 获取 Tmp 目录路径

//获取Tmp目录  
-(void)dirTmp{  
    //[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];  
    NSString *tmpDirectory = NSTemporaryDirectory();  
    NSLog(@"app_home_tmp: %@",tmpDirectory);  
}  
6. 创建文件夹

//创建文件夹  
-(void *)createDir{  
    NSString *documentsPath =[self dirDoc];  
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    // 创建目录  
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];  
    if (res) {  
        NSLog(@"文件夹创建成功");  
    }else  
        NSLog(@"文件夹创建失败");  
 }  
7. 创建文件

//创建文件  
-(void *)createFile{  
    NSString *documentsPath =[self dirDoc];  
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
    BOOL res=[fileManager createFileAtPath:testPath contents:nil attributes:nil];  
    if (res) {  
        NSLog(@"文件创建成功: %@" ,testPath);  
    }else  
        NSLog(@"文件创建失败");  
}  
8. 写数据到文件: 

//写文件  
-(void)writeFile{  
    NSString *documentsPath =[self dirDoc];  
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
    NSString *content=@"测试写入内容!";  
    BOOL res=[content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];  
    if (res) {  
        NSLog(@"文件写入成功");  
    }else  
        NSLog(@"文件写入失败");  
}  
9. 读文件数据:

//读文件  
-(void)readFile{  
    NSString *documentsPath =[self dirDoc];  
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
//    NSData *data = [NSData dataWithContentsOfFile:testPath];  
//    NSLog(@"文件读取成功: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);  
    NSString *content=[NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];  
    NSLog(@"文件读取成功: %@",content);  
}  
10. 文件属性:

//文件属性  
-(void)fileAttriutes{  
    NSString *documentsPath =[self dirDoc];  
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];     
    NSArray *keys;  
    id key, value;  
    keys = [fileAttributes allKeys];  
    int count = [keys count];  
    for (int i = 0; i < count; i++)  
    {  
        key = [keys objectAtIndex: i];  
        value = [fileAttributes objectForKey: key];  
        NSLog (@"Key: %@ for value: %@", key, value);  
    }  
}  
11. 删除文件:

//删除文件  
-(void)deleteFile{  
    NSString *documentsPath =[self dirDoc];  
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];     
    BOOL res=[fileManager removeItemAtPath:testPath error:nil];  
    if (res) {  
        NSLog(@"文件删除成功");  
    }else  
        NSLog(@"文件删除失败");     
    NSLog(@"文件是否存在: %@",[fileManager isExecutableFileAtPath:testPath]?@"YES":@"NO");  
}  

另: NSFileManager 是线程安全的, 可以在多线程中放心的使用.

计算沙盒中目录的大小: 

+(NSString*)getCacheSize
{
    NSDate* begin = [NSDate date];
    NSFileManager* fm = [NSFileManager defaultManager];
    __block NSError* error = nil;
    __block NSUInteger fileSize = 0;
    //获取Books的缓存
    dispatch_sync(queue, ^{
        NSArray* subFiles = [fm subpathsAtPath:BOOKHEADERPath([LoginPlugin share].userID)];
        NSLog(@"subpath = %@",subFiles);
        for (NSString* fileName in subFiles) {
            if ([fileName hasSuffix:@"png"]||[fileName hasSuffix:@"jpg"]) {
                NSDictionary* dic = [fm attributesOfItemAtPath:BOOKPATH([LoginPlugin share].userID,fileName) error:&error];
                NSUInteger size = (error ? 0:[dic fileSize]);
                fileSize += size;
            }
        }
    });
    NSString* cacheString = [NSString stringWithFormat:@"%.1fM",fileSize/(1024.0*1024)];
    NSTimeInterval time = [begin timeIntervalSinceNow];
    NSLog(@"便利文件耗费时间:%lf",time/60.0);
    return cacheString;
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值