数据持久化--沙盒

沙盒机制,需要对属性进行编码和反编码

定义一个Person类

在.h文件中声明几个属性(注意需要遵守一个NSCoding协议)

#import <Foundation/Foundation.h>

//实现编码和反编码需要遵守协议NSCoding
@interface Person : NSObject<NSCoding>

@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)NSString *sex;
@property(nonatomic,retain)NSString  *age;

@end

在.m文件里对类中属性进行编码和反编码

#import "Person.h"

@implementation Person

-(void)dealloc
{
    [self.name release];
    [self.sex release];
    [super dealloc];
}

#pragma mark-------对类中所有属性进行编码
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.sex forKey:@"sex"];
    [aCoder encodeObject:self.age forKey:@"age"];
}

#pragma mark-------对类中所有属性进行反编码
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeObjectForKey:@"age"];
        self.sex = [aDecoder decodeObjectForKey:@"sex"];
        
    }
    return self;
}


@end

下面直接给出沙盒使用代码:

//1.获取应用程序沙盒中Document文件夹
    //第一种方式:
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSLog(@"%@",documentPath);
    //第二种方式:
    //获取你的应用程序的沙盒文件夹
    NSString *homePath = NSHomeDirectory();
    NSLog(@"homePath:%@",homePath);
    NSString *documentsPath1 = [homePath stringByAppendingPathComponent:@"Documents"];
    NSLog(@"%@",documentsPath1);
    
    //查看应用程序包XXX.app
    NSLog(@".app =%@",[NSBundle mainBundle].resourcePath);
    
#pragma mark------简单对象写入文件
//一.向一个文件中写入字符串
    NSString *string = @"I love you very much!";
    //1.拼接文件路径
    NSString * filePath = [documentPath stringByAppendingPathComponent:@"note.txt"];
    //2.将字符串写入文件
     [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",filePath);
    //3.读取文件中的字符串
    NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str);
    
//二.向文件内写入数组
    //1.拼接文件存储的路径
    NSString * arrayPath = [documentPath stringByAppendingPathComponent:@"array.txt"];
    //数据
    NSArray *array = [NSArray arrayWithObjects:@"abc",@"dce",@"ghj", nil];
    //2.将数组写入文件
    [array writeToFile:arrayPath atomically:YES];
    NSLog(@"%@",arrayPath);
    //3.从文件中读取数组
    NSArray *arr = [NSArray arrayWithContentsOfFile:arrayPath];
    NSLog(@"%@",arr);
    
//三.向文件内写入字典
    //1.拼接文件存储路径
    NSString * dicPath = [documentPath stringByAppendingPathComponent:@"dic.txt"];
    //数据
    NSDictionary *dic = @{@"abc":@"123",@"bcd":@"456",@"efg":@"789"};
    //2.将字典写入文件
    [dic writeToFile:dicPath atomically:YES];
    NSLog(@"%@",dicPath);
    //3.从文件中读取字典
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:dicPath];
    NSLog(@"%@",dict);
    
//四.向文件中写入NSData类型数据
    //数据
    UIImage *image = [UIImage imageNamed:@"879.jpg"];
    //将UIImage类型对象转换为NSData类型的数据
    NSData * data = UIImageJPEGRepresentation(image, 1);
    //1.拼接文件路径
    NSString * dataPath = [documentPath stringByAppendingPathComponent:@"data.plist"];
    //2.写入文件
    [data writeToFile:dataPath atomically:YES];
    NSLog(@"%@",dataPath);
    //3.从文件中读取NSData文件
    NSData * data1 = [NSData dataWithContentsOfFile:dataPath];
    NSLog(@"%@",data1);
    
    UIImage *image1 = [UIImage imageWithData:data1];
    NSLog(@"%@",image1);
    
#pragma mark------NSFileManager管理文件类
    //1.创建文件夹
    //拼接路径(在哪个文件夹下面创建新的文件夹,文件夹的名字是什么)
    NSString * path1 = [documentPath stringByAppendingPathComponent:@"path1"];
    //创建文件夹
    NSDictionary *dic2 = @{@"createTime":@"2015-5-8"};
    [[NSFileManager defaultManager] createDirectoryAtPath:path1 withIntermediateDirectories:YES attributes:dic2 error:nil];
    //在新创建的文件夹里写入文件
    NSString * path2 = [path1 stringByAppendingPathComponent:@"like.plist"];
    [[NSFileManager defaultManager] createFileAtPath:path2 contents:data attributes:dic2];
    NSLog(@"%@",path2);
    
#pragma mark----在Library/Caches下创建path文件夹,在path文件夹下创建image.txt文件
    //获取文件夹路径(library/caches)
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    //拼接path文件夹路径
    NSString * path = [cachesPath stringByAppendingPathComponent:@"path"];
    //创建path文件夹
    NSDictionary * dict1 = @{@"createTime":@"2015-5-8"};
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:dict1 error:nil];
    //在新文件夹里写入文件(拼接文件路径)
    NSString * image2 = [path stringByAppendingPathComponent:@"image.txt"];
    //创建文件
    [[NSFileManager defaultManager] createFileAtPath:image2 contents:data attributes:dict1];
    NSLog(@"%@",image2);

#pragma mark------删除文件
    //①.判断需要删除的文件是否存在
    BOOL flag = [[NSFileManager defaultManager] fileExistsAtPath:cachesPath];
    NSLog(@"%d",flag);
    //②.如果文件存在,删除它
    if (flag) {
        [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    }
    
    BOOL flag1 = [[NSFileManager defaultManager] fileExistsAtPath:cachesPath];
    NSLog(@"++%d",flag1);
    
#pragma mark-------对复杂对象进行数据持久化
#pragma mark-------将复杂对象存储文件的过程:(复杂对象->归档->NSData->拼接文件路径->writeToFile写入)
    Person *person = [[Person alloc]init];
    person.name = @"zhangsan";
    person.age = @"20";
    person.sex = @"男";
    //创建一个可变的NSMutableData对象,用来存放person对象被归档之后的data数据的.
    NSMutableData * personData = [NSMutableData data];
    //创建一个归档工具对象
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:personData];
    //开始对person对象进行归档(把person对象转换为NSData类型)
     [archiver encodeObject:person forKey:@"person"];
    //注意:当归档结束时,一定要调用finishEncoding
    [archiver finishEncoding];
    //完成转换了,此时personData存放的就是person对象被归档之后的NSData类型的数据
    //拼接存放数据的文件路径
    NSString * personPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString * personPath1 = [personPath stringByAppendingPathComponent:@"person.txt"];
    //将归档之后的personData数据写入person.txt中
    [personData writeToFile:personPath1 atomically:YES];
    NSLog(@"%@",personPath1);
    
#pragma mark-------从文件中读取复杂对象的过程:(获取文件路径->读取NSData数据->反归档->得到复杂对象)
    NSData * data3 = [NSData dataWithContentsOfFile:personPath1];
    //创建一个反归档工具对象
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data3];
    //开始对NSData类型数据进行反归档(将data类型数据转换为复杂对象)
    Person *person1 = [unarchiver decodeObjectForKey:@"person"];
    NSLog(@"+++%@",person1.name);
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值