您的位置:首页 > 产品设计 > UI/UE

iOS UI16_数据持久化

2015-08-20 09:12 302 查看
//
//  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: