iOS UI16_数据持久化

来源:互联网 发布:网站域名多少钱一年 编辑:程序博客网 时间:2024/05/05 05:15
////  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
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 一岁宝宝骨盆不对称怎么办 入盆了又出来了怎么办 大腿前突小腿后怎么办 英语不好高二了怎么办 断奶后又复吸怎么办 招联金融综合评定不足怎么办 git本地分支比远程高怎么办 娃儿上嘴唇里面破了怎么办 错过了各大招聘怎么办 优秀团员申请表没有获奖情况怎么办 大学生毕业学生登记表涂改了怎么办 c语言挂科了怎么办 吸入腐蚀性气体鼻子流血了怎么办 腰劳损痛的厉害怎么办 两个宝宝斜颈左边力量差怎么办 姿势不正确引起的习惯性斜颈怎么办 一岁宝宝有点斜颈怎么办 六个月宝宝有点斜颈怎么办 5月宝宝有点斜颈怎么办 半岁宝宝头偏怎么办 肌性斜颈成年后怎么办 5个月孩子脖子歪怎么办 宝宝一岁多头歪怎么办 四个月宝宝歪脖子怎么办 1岁宝宝脖子歪怎么办 宝宝脖子是歪的怎么办 小孩脖子睡歪了怎么办 脸部三角区肿了怎么办 面部三角区挤了怎么办 胳膊扭着了肿了怎么办 多囊卵巢综合症治不好怎么办 胳膊受了风发麻怎么办 胳膊抻筋了很疼怎么办 腰抻了怎么办最有效 孩子胳膊抻着了怎么办 胳膊伤筋了疼怎么办 宝宝胳膊抻了疼怎么办 练完普拉提头晕怎么办 生完孩子腰背疼怎么办 宝宝不肯把屎尿怎么办 存的电话删除了怎么办