数据持久化

先上几个图片解释一下什么是沙盒

这里写图片描述

这里写图片描述
这里写图片描述

这里写图片描述
这里写图片描述

然后是简单对象的数据持久化,复杂对象数据持久化,要继承一个协议
NSCopying,重写里面的两个方法。

- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder; // NS_DESIGNATED_INITIALIZER

下面直接上代码

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

#pragma mark -------------获取沙盒下的文件目录

    //1.获取沙盒中Documents这个文件夹得路径

    //第一种方式

    NSString *documentsPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES).lastObject;


    NSLog(@"%@",documentsPath);


    //第二种方式

     NSString *user =  NSHomeDirectory();

    NSString *documentPath1 = [user stringByAppendingPathComponent:@"Documents"];

    NSLog(@"%@",documentPath1);

    //获取应用程序包
    NSLog(@"%@",[NSBundle mainBundle].resourcePath);

#pragma mark------------简单对象持久化

    NSString *string = @"I love you so much";

    //1.存储路径

    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"string.txt"];

    //2.将字符串写入文件

    [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];


    //3.读取文件中的字符串
    NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",str);

    //4.将数组写入未见

#warning mark ------------如果想把数组array直接写入文件,数组中的文件必须是简单对象(NSString,NSArray)

    //1.拼接存储路径

    NSString *arrPath = [documentsPath stringByAppendingPathComponent:@"array.txt"];
    NSArray *arr = @[@"a",@"b",@"c"];

    //2.写入文件
    [arr writeToFile:arrPath atomically:YES];

    //3.从文件中读取数组

    NSArray *array = [NSArray arrayWithContentsOfFile:arrPath];

    NSLog(@"%@",array);

//将字典持久化
    NSDictionary *dic = @{@"name":@"张三",@"age":@"19",@"sex":@"男"};

    NSString *dicPath = [documentsPath stringByAppendingPathComponent:@"dictionary.txt"];

    [dic writeToFile:dicPath atomically:YES];

    NSLog(@"%@",dicPath);

    NSDictionary *testDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];

    for (NSString *key in testDic) {
        NSLog(@"%@",[testDic objectForKey:key]);
    }

    //将NSData数据持久化

    UIImage *image = [UIImage imageNamed:@"1.jpg"];

    NSData *data = UIImageJPEGRepresentation(image, 1.0);


    //存储数据

    NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"data.txt"];

    [data writeToFile:dataPath atomically:YES];


#pragma mark ----------NSFileManager(文件管理类)

    //获取缓存文件夹所在路径

    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

    NSDictionary *dic1 = @{@"name":@"李四"};


    //在cachesPath路径下创建一个文件夹

    NSString *directoryPath = [cachesPath stringByAppendingPathComponent:@"path"];


    //创建一个文件管理器对象
    NSFileManager *fielMager = [NSFileManager defaultManager];

    //根据路径创建文件夹

    NSDictionary *fileData = @{@"createTime":@"2015-9-9"};

    [fielMager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:fileData error:nil];

    //拼接存储路径,存到文件中,而不是存到文件夹中
    NSString *dicPath1 = [directoryPath stringByAppendingPathComponent:@"dic.jpg"];

    [dic1 writeToFile:dicPath1 atomically:YES];

    //创建文件,这个方法存储的数据是NSData
    [fielMager createFileAtPath:dicPath1 contents:data attributes:fileData];


    //删除指定的文件,先判断给定的文件路径是否真实存在
    if ([fielMager fileExistsAtPath:dicPath1]) {

        NSLog(@"%d",[fielMager fileExistsAtPath:dicPath1]);

        [fielMager removeItemAtPath:dicPath1 error:nil];
    }


#pragma mark -------------NSUserDefaults 也是单例类

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setValue:@"yaxin" forKey:@"name"];

    [defaults setValue:@"123" forKey:@"password"];

    //立即同步到文件中
    [defaults synchronize];

    NSString *name = [defaults valueForKey:@"name"];

    NSString *pwd = [defaults valueForKey:@"password"];

    NSLog(@"%@,    %@",name,pwd);


#pragma mark ------------复杂对象持久化

    //过程:(复杂对象->归档->NSData->writeToFile)
    Person *person = [[Person alloc]init];
    person.name = @"张三";
    person.gender = @"男";
    person.age = 23;

    NSMutableData *mutData = [NSMutableData data];
    //创建归档器
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mutData];

    //进行归档
    [archiver encodeObject:person forKey:@"person"];

    //结束归档
    [archiver finishEncoding];

    //将归档之后的NSData数据,写入文件
    //①存储路径
    NSString *personPath = [cachesPath stringByAppendingPathComponent:@"person.txt"];
    //②写入文件

    [mutData writeToFile:personPath atomically:YES];

    NSLog(@"%@",mutData);

#pragma mark --------------反归档(读取复杂对象)

    //过程:(读取文件->NSData - >反归档-》复杂对象那个)
    //从文件中读取NSData数据

    NSData *personData = [NSData dataWithContentsOfFile:personPath];

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:personData];

    //使用反归档工具对resultData数据进行反归档

    Person *person1 = [unarchiver decodeObjectForKey:@"person"];

    //结束反归档
    [unarchiver finishDecoding];

    NSLog(@"%@,%@,%lu",person1.name,person1.gender,person1.age);

    // Do any additional setup after loading the view, typically from a nib.
}

对于复杂对象

#import <Foundation/Foundation.h>

//复杂对象归档第一步:遵守NSCoding协议
@class Dog;
@interface Person : NSObject<NSCopying>



@property(nonatomic,retain)NSString * name;
@property(nonatomic,retain)NSString * gender;
@property(nonatomic,assign)NSInteger age;

@property(nonatomic,retain)Dog * dog;

@end


#import "Person.h"

@implementation Person


#pragma mark ===========进行编码
- (void)encodeWithCoder:(NSCoder *)aCoder  //aCoder就是编码器
{
    //编码
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.gender forKey:@"gender"];
    [aCoder encodeInteger:self.age forKey:@"age"];
//    [aCoder encodeObject:self.dog forKey:@"dog"];     //在dog的那边也要归档

}


#pragma mark --------------进行反编码
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.name  = [aDecoder decodeObjectForKey:@"name"];
        self.gender = [aDecoder decodeObjectForKey:@"gender"];
        self.age = [aDecoder decodeIntegerForKey:@"age" ];
//        self.dog = [aDecoder decodeObjectForKey:@"dog"];     //在dog的那边也要反归档
    }

    return self;
}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值