iOS UI16_数据持久化

//
//  Student.h
//  UI16_数据持久化
//
//  Created by dllo on 15/8/19.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import <Foundation/Foundation.h>
#pragma mark 假设想实现归档和反归档的操作须要先签订一个协议NSCoding
@interface Student : NSObject<NSCoding>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *sex;
@property(nonatomic,assign)NSInteger age;
@property(nonatomic,copy)NSString *hobby;

//针对这四条属性,写一个自己定义初始化方法和便利构造器

-(instancetype)initWithName:(NSString *)name
                sex:(NSString *)sex
                age:(NSInteger)age
              hobby:(NSString *)hobby;

+(instancetype)studentWithName:(NSString *)name
                 sex:(NSString *)sex
                 age:(NSInteger)age
               hobby:(NSString *)hobby;


@end
//
//  Student.m
//  UI16_数据持久化
//
//  Created by dllo on 15/8/19.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import "Student.h"

@implementation Student

-(instancetype)initWithName:(NSString *)name
                sex:(NSString *)sex
                age:(NSInteger)age
              hobby:(NSString *)hobby
{
    self=[super init];
    if (self) {
        _age =age;
        _name =name;
        _hobby =hobby;
        _sex =sex;
    }
    return self;
}

+(instancetype)studentWithName:(NSString *)name
                           sex:(NSString *)sex
                           age:(NSInteger)age
                         hobby:(NSString *)hobby
{
    Student *stu = [[Student alloc] initWithName:name sex:sex age:age hobby:hobby];
    return stu;
}

#pragma mark 签订完NSCoding协议之后,须要实现两个协议方法,一个是归档的时候使用的,一个是反归档的时候使用的
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"姓名"];
    [aCoder encodeInteger:self.age forKey:@"年龄"];
    [aCoder encodeObject:self.hobby forKey:@"爱好"];
    [aCoder encodeObject:self.sex forKey:@"性别"];
    //使用encode方法要和数据的类型相互匹配
}


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        //把数据依据之前的key再反编译回来
        self.name = [aDecoder decodeObjectForKey:@"姓名"];
        self.age = [aDecoder decodeIntegerForKey:@"年龄"];
        self.hobby = [aDecoder decodeObjectForKey:@"爱好"];
        self.sex = [aDecoder decodeObjectForKey:@"性别"];

    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
//
//  ViewController.m
//  UI16_数据持久化
//
//  Created by dllo on 15/8/19.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import "ViewController.h"
#import "Student.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //苹果手机为了保证自己数据上的绝对安全,设计了沙盒文件,每个应用程序上都配备了自己的沙盒文件,每一次执行,目录的名字就会变成一个没有不论什么规律的字符串
    //第一个參数:当前要前往那一个目录,前往documents文件用NSDocuemtDirectory,64行那个,还能够前往caches目录,相应68行
    //第二个參数:訪问的目录类型,指定訪问是用户目录
    //第三个參数:绝对路径(YES),相对路径(NO)
    //绝对路径是给系统使用的,系统能够依据当前的路径找到目录,我们在操作目录时是绝对路径
    //相对路径仅仅会把要前往的目录显示,其它部分都是~,告诉程序猿要去哪个目录
//    NSArray *sandbox =NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSLog(@"%@",sandbox[0]);
    //沙盒里一共同拥有三个文件
    //1.是Documents文件:主要用来存储用户的想要存储的一些信息,比方收藏的信息或者自己设置的一些内容,所以我们做收藏功能就是前往这个目录里写文件
    //2.Library目录里是方便程序开发人员的,主要操作它里面的两个目录,caches和Preferences
    //caches:用来保存缓存文件,SDWebImage会把图片加到缓存文件里,所以清除缓存功能就是把这个目录删除
    //Preferences:一般来保存程序猿设置的信息,比方NSUserDefults就会把数据保存在这个目录里
    //3.tmp文件:一般存放暂时内容
    //之前在沙盒里另一个.app文件,在新的版本号里已经被移走了
    //把简单对象写入到本地,简单对象指的是NSString,NSArray

//    //1.先通过数组获取沙盒路径
//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    //从数组里获取沙盒路径
//    NSString *sandBoxPath =sandbox[0];
//    //要给写入的文件拼接一个路径,拼接方式有两种
////    NSString *documentPath = [sandBoxPath stringByAppendingString:@"/顾宇.txt"];
//    
//    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"顾宇.xml"];
//    NSLog(@"%@",documentPath);

//    NSString *str = @"书山有路勤为径,学海无涯苦作舟";
//    //把字符串写入到本地
//    //第一个參数:文件要保存的路径
//    //第二个參数:对文件进行保护YES
//    //第三个參数:编码
//    //第四个參数,错误信息
//    [str writeToFile:documentPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//    //假设路径下有相应的文件,则会把原来文件覆盖,假设没有则创建一个新文件
//    //把沙盒文件读出来
//    NSString *temoStr = [NSString stringWithContentsOfFile:documentPath encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@",temoStr);

//    //把数组写入到本地
//    NSArray *arr =@[@"1",@"2",@"3",@"4",@"5",@"6"];
//    //通过数组获取沙盒地址
//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    //用字符串保存沙盒路径
//    NSString *sandboxPath = sandbox[0];
//    //给要写入的文件拼接路径
//    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"哈哈.plist"];
//    //把数组写入到本地
//    [arr writeToFile:documentPath atomically:YES];
//    NSLog(@"%@",documentPath);
//    
//    //把数组读出来
//    NSArray *temp = [NSArray arrayWithContentsOfFile:documentPath];
//    NSLog(@"%@",temp);

//    //把字典写入到本地
//    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"2", nil];
//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *sandboxPath = sandbox[0];
//    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"嘿嘿"];
//    [dic writeToFile:documentPath atomically:YES];
//    NSLog(@"%@",documentPath);
//    
//    NSDictionary *temp = [NSDictionary dictionaryWithContentsOfFile:documentPath];
//    NSLog(@"%@",temp);


    //复杂对象写入到本地,主要指我们自己创建的对象写入到本地,也叫归档和犯反归档操作


    //创建对象呢
//    Student *stu1 = [Student studentWithName:@"张三" sex:@"男" age:14 hobby:@"玩"];


//    //1.通过数组获取沙盒路径
//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    //2.用字符串截取沙盒路径
//    NSString *sandBoxPath = sandbox[0];
//    //3.拼接目录路径,这个目录扩展名是随意的
//    NSString *decomentPath = [sandBoxPath stringByAppendingPathComponent:@"学生.avi"];
//    //对对象进行归档操作
//    //第一个參数:要实施归档的对象
//    //第二个參数:路径
//    [NSKeyedArchiver archiveRootObject:stu1 toFile:decomentPath];
//    NSLog(@"%@",decomentPath);
//    
//    //反归档
//    Student *newStu = [NSKeyedUnarchiver unarchiveObjectWithFile:decomentPath];
//    NSLog(@"%@",newStu.name);


//    //创建三个学生
//    Student *stu1 = [Student studentWithName:@"张三" sex:@"男" age:14 hobby:@"玩"];
//    Student *stu2 = [Student studentWithName:@"李四" sex:@"女" age:15 hobby:@"睡觉"];
//    Student *stu3 = [Student studentWithName:@"神六" sex:@"男" age:16 hobby:@"唱歌"];
//    NSArray *array = @[stu1,stu2,stu3];
//    
//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
//    NSString *sandboxPath = sandbox[0];
//    //拼接文件路径
//    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"曹军.plist"];
//    //归档操作
//    [NSKeyedArchiver archiveRootObject:array toFile:documentPath];
//    NSLog(@"%@",documentPath);
//    
//    //反归档,遍历学生姓名
//    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
//    for (Student *temp in arr) {
//        NSLog(@"%@",temp.name);
//    }

#warning 总结:数据持久化的步骤
    //1.指定前往那一个目录
    //2.用字符串接收路径
    //3.拼接文件路径
    //4.写入本地或归档操作
    //注;假设是复杂对象归档,要签订NSCoding协议,而且实现两个协议方法,放在数组里的复杂对象归档也要签协议


//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:@"123456" forKey:@"password"];
//    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
//    NSLog(@"%@",sandBox[0]);
//    NSLog(@"%@",[defaults objectForKey:@"password"]);
    //NSUserDefaults一般存放的是小的数据,比方字符串等,它的使用方法和字典相似

    //通过文件管理者对目录进行操作
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
    NSString *sandBoxPath =sandBox[0];
    //创建一个文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    //给要创建的目录拼接一个路径
    NSString *filePath = [sandBoxPath stringByAppendingPathComponent:@"guyu"];
    //目录的名不须要扩展名
    //通过manager进行目录的创建
    [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    NSLog(@"%@",filePath);
    //向目录里写入一个字符串
    NSString *documentPath = [filePath stringByAppendingPathComponent:@"字符串.txt"];
    NSString *str = @"我是字符串";
    [str writeToFile:documentPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    //移除目录
//    [manager removeItemAtPath:filePath error:nil];
//
    //清除缓存
    NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES);
    NSString *cachePath =cache[0];
    [manager removeItemAtPath:cachePath error:nil];


}


@end
原文地址:https://www.cnblogs.com/cynchanpin/p/7084143.html