iOS进阶——沙盒及沙盒路径、简单文件的写入

       iOS每个应用程序都有独立的空间作为其运行存储的地方,不同应用之间不允许互相访问其空间,在iOS8.0之后,逐步开放了部分权限。

一、获取程序沙盒主路径的方法

//沙盒的主路径
    NSString* homeStrPath = NSHomeDirectory();
    NSLog(@"home--%@",homeStrPath);

 //通过search函数得到doctoments文件的路径
    /**
     *  Description
     *
     *  @param NSDocumentDirectory 所搜寻的文件夹得主路径
     *  @param NSUserDomainMask    搜索范围,此参数是规定搜素区域为沙盒下的
     *  @param YES                 是否展开,如果是NO的话,是一个~,yes则是完整的路径
     *
     *  @return 是一个路径数组的详细信息
     */
    NSArray *documentArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);
    NSString *tem=[documentArr objectAtIndex:0];
    NSLog(@"searchDocuments -- %@",tem);

二、简单对象的读写操作

iOS中提供的4种类型可以直接进行文件的存取:
NSString(字符串);
NSArray (数组);
NSDictionary(字典);
NSdata (数据);
(以上包括其子类型)。

数组、字典一般写入为plist后缀的文件,字符串为text文件,而数据类型的文件写入时,不需要加后缀名保存。

三、文件管理器与文件对接器

iOS进阶——沙盒及沙盒路径、简单文件的写入_第1张图片
文件管理器:
//创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isCreate = [fileManager createDirectoryAtPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"test"]withIntermediateDirectories:YES attributes:nil error:nil];
    if (isCreate) {
        NSLog(@"goodMan,successful--%@",[SandBoxPaths documentsPath]);
    }else{
        NSLog(@"default");
    }
    BOOL isMoved = [fileManager moveItemAtPath:[SandBoxPaths documentsPath] toPath:[[SandBoxPaths cachesPath] stringByAppendingPathComponent:@"test"] error:nil];
    if (isMoved) {
        NSLog(@"成功");
    }

// 复制文件
        BOOL isCopy = [fileManager copyItemAtPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"text.txt"]toPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"test/text.txt"] error:nil];
        if (isCopy) {
            NSLog(@"复制成功");
        }else{
            NSLog(@"复制失败");
        }
    //判断文件是否相等
    BOOL isEaqul = [fileManager contentsEqualAtPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"text.txt"] andPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"text.txt"]];
    if (isEaqul) {
        NSLog(@"一致");
    }else{
        NSLog(@"不一致");
    }
    //删除文件
    [fileManager removeItemAtPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"text.txt"] error:nil];
    BOOL isExists = [fileManager fileExistsAtPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"text.txt"]];
    if (isExists) {
        NSLog(@"存在");
    }else{
        NSLog(@"不存在");
    }

文件对接器:
//    创建一个准备读取的handle对象
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:[[SandBoxPaths documentsPath]stringByAppendingPathComponent:@"handle.txt"]];
//    完整读取文件
    NSData *endData = [readHandle readDataToEndOfFile];
    NSString *string = [[NSString alloc]initWithData:endData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",string);
    
    NSData *lenthData = [readHandle readDataOfLength:8];
    NSString *string7 = [[NSString alloc]initWithData:lenthData encoding:NSUTF8StringEncoding];
    NSLog(@"特定长度%@",string7);
    
    NSInteger lenth = [[readHandle availableData] length];
    NSLog(@"%ld",lenth);
//    创建一个可以写入的文件对象
    NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"handle.txt"]];
    //改变文件的偏移量
    [writeHandle seekToFileOffset:3];
    [writeHandle writeData:[@"5678" dataUsingEncoding:NSUTF8StringEncoding]];
    //从指定路径下读取文件
    NSString* result = [NSString stringWithContentsOfFile:[[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"handle.txt"] encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",result);

四、复杂对象的读写


<span style="font-size:14px;">//归档方法
-(void)archiver{
    //创建需要归档的对象
    UserInfoModel *boy = [[UserInfoModel alloc]init];
    boy.name = @"sb";
    boy.gender = @"ooo";
    boy.age = @"16";
    boy.phoneNum = @"11111111111";
    boy.headImage = nil;
    //创建一个可变的data对象,用来存储复杂兑现
    NSMutableData *data = [NSMutableData data];//用来接收转换好之后的复杂对对象的容器
    //归档
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:boy forKey:@"boy"];
    //归档结束,只有调用了此方法,才会存储为data类型
    [archiver finishEncoding];
    //将归档结束后的数据进行持久化
    //构造存储路径
    //存到cache里
    
    NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesPath = [[caches objectAtIndex:0] stringByAppendingPathComponent:@"data"];
    
    //存储数据
    [data writeToFile:cachesPath atomically:YES];
    
}</span>

<span style="font-size:14px;">//反归档,将归档好的NSData类型转化为复杂对象
-(void)enarchiver{
    NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesPath = [[caches objectAtIndex:0]stringByAppendingPathComponent:@"data"];
    
    NSData *data = [NSData dataWithContentsOfFile:cachesPath];
    
    //反归档工具
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    UserInfoModel *boy = [unArchiver decodeObjectForKey:@"boy"];
    [unArchiver finishDecoding];
    NSLog(@"name -- %@",boy.name);
}</span>

//归档遵循的协议
@interface UserInfoModel : NSObject<NSCoding>

//实现协议的代理方法,在这里是对属性的编码
//写此方法防止奔溃因字典的键值不匹配问题
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
}

//归档的协议方法,实际上是对当前类对象所有的属性进行归档,协议方法在我们归档的时候会自动调用
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.age forKey:@"age"];
    [aCoder encodeObject:self.gender forKey:@"gender"];
    [aCoder encodeObject:self.phoneNum forKey:@"phoneNum"];
    [aCoder encodeObject:self.headImage forKey:@"headImage"];
    NSLog(@"归档的方法已经调用");
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeObjectForKey:@"age"];
        self.gender = [aDecoder decodeObjectForKey:@"gender"];
        self.phoneNum = [aDecoder decodeObjectForKey:@"phoneNum"];
        self.headImage = [aDecoder decodeObjectForKey:@"headimage"];
    }
    NSLog(@"解档调用");
    
    return self;
}


你可能感兴趣的:(ios开发,沙盒)