初级数据持久化

1.沙盒机制

通过代码查找程序沙盒相对路径,返回类型是NSArray;

NSArray * arr =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",arr);

2.简单写入文件。

1.NSString 写入文件

1.1获取document文件夹路径。

    //1.NSString 写入文件
    //1.1获取document文件夹路径
//    NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//    NSLog(@"%@",docPath);
//    //1.2在document路径下创建user.txt文件路径
//    NSString * filePath = [docPath stringByAppendingString:@"/user.txt"];
//    //1.3将字符串写入文件
//    NSString * userName = @"zhangsan";
//    [userName writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//    //从文件读取内容
//    NSString * str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@",str);
 

2.数组写入文件

//2.数组写入文件
    //获取document文件夹路径
//    NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//    NSLog(@"%@",docPath);
//    //2.2在document文件夹下创建arr.txt文件路径.以下两种方式都可以
//    NSString * filePath = [docPath stringByAppendingPathComponent:@"arr.txt"];
////    NSString * filePath = [docPath stringByAppendingString:@"/arr.txt"];
//    //2.3创建数组写入文件。
//    NSArray * arr = @[@"zhangsan",@"lisi",@"hehe",@"lili"];
//    [arr writeToFile:filePath atomically:YES];

3.字典写入文件

   //3.字典写入文件
    //3.1获取document路径
//    NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//    //3.2在document 文件夹下创建dic.aaa文件
//    NSString * filePath = [docPath stringByAppendingPathComponent:@"dic.aaa"];
//    //3.3创建字典写入文件
//    NSDictionary * dic = @{@"name": @"张三",@"sex":@"男",@"age":@"23"};
//    [dic writeToFile:filePath atomically:YES];

4.把图片转化成二进制写入文件

//    //4.NSData写入文件
//    NSString * Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//    NSLog(@"%@",Path);
//    NSString * dataPath = [Path stringByAppendingPathComponent:@"data.txt"];
//    UIImage * img = [UIImage imageNamed:@"1.png"];
//   NSData * data = UIImagePNGRepresentation(img);
//
//    [data writeToFile:dataPath atomically:YES];

把内容写入文件都会执行writeToFile:atomically: 方法。

二、复杂对象写入文件。

复杂对象没有writeTofile方法,所以不能直接写入文件,解决这一问题的思路是:将复杂对象转化为简单对象 然后调用简单对象的writeTofile方法实现持久化

NSKeyedArchiver类是归档类 其主要功能是将对象转化成NSData类型的对象

NSKeyedUNArchiver类是反归档类,其主要功能是将二进制数据还原成对象。

被归档类的对象,必修遵循NSCoding协议 实现协议里的方法。

1.先建立一个类,继承自NSObject

声明属性;

@interface User : NSObject<NSCoding> 遵循协议

@property(nonatomic,copy)NSString * name;
@property(nonatomic,copy)NSString * pwd;
@property(nonatomic,assign) int  status;

在.m文件中实现方法

#import "User.h"

@implementation User

-(void)dealloc
{
    [_name release];
    [_pwd release];
    [super dealloc];
}
//归档时调用,对属性进行编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.pwd forKey:@"pwd"];
    [aCoder encodeInt:self.status forKey:@"status"];

}
//在返归档时调用,从data数据中解码属性。
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.pwd = [aDecoder decodeObjectForKey:@"pwd"];
        self.status = [aDecoder decodeIntForKey:@"status"];
    }
    return self;
}
@end

然后在ViewController里引用刚才创建的类,实现归档

//    User * usr = [[User alloc]init];
//    usr.name = @"李四";
//    usr.pwd = @"212343";
    //归档
//    //1.创建MutableData对象用于接收归档数据
//    NSMutableData * muldata = [NSMutableData data];
//    //2.创建归档类。
//    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:muldata];
//    //3.开始归档(编码)
//    [archiver encodeObject:usr forKey:@"usr"];
//    //4.结束编码,将编码数据写到muldata中。
//    [archiver finishEncoding];
//    NSLog(@"%@",muldata);

反归档是把文件里面的内容打印出来。

//1.创建反归档类
//    NSKeyedUnarchiver * unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:muldata];
//    //2.开始解码。
//   User * deUsr = [unArchiver decodeObjectForKey:@"usr"];
//    //3.完成解码。
//    [unArchiver finishDecoding];
//    NSLog(@"%@ %@ %d",deUsr.name,deUsr.pwd,deUsr.status);

归档和反归档可以直接用一句话来实现

//    //归档。
//    NSString * filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingString:@"/archive.txt"];
//    [NSKeyedArchiver archiveRootObject:usr toFile:filePath];//    //反归档、
//    User * test = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
//    NSLog(@"-------%@ %@ %d",test.name,test.pwd,test.status);

NSFileManager的使用

NSFileManager对象允许您可以检查文件系统的内容,并对其进行更改。文件管理器对象通常是您第一次与文件系统交互。您可以使用它来查找、 创建、 复制和移动文件和目录。您还使用它来获取有关某个文件或目录的信息或更改其属性的一部分。

//创建文件管理器。
    NSFileManager * manager = [NSFileManager defaultManager];
    NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"%@",docPath);
    //创建起始文件夹。
    NSString * newPath = [docPath stringByAppendingString:@"/new"];
    [manager createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:nil];
    //在起始文件夹里创建文件。
    NSString * filePath = [newPath stringByAppendingString:@"/new.txt"];
    NSString * str = @"mini";
    [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    //创建目的地文件夹
    NSString * aimPath = [docPath stringByAppendingString:@"/aim"];
    [manager createDirectoryAtPath:aimPath withIntermediateDirectories:YES attributes:nil error:nil];
    //创建目的地文件。
    NSString * strPath = [aimPath stringByAppendingString:@"/new.txt"];
    BOOL isres= [manager removeItemAtPath:strPath error:nil];
    if (isres) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }

    BOOL isCopy = [manager copyItemAtPath:filePath toPath:strPath error:nil];
    if (isCopy) {
        NSLog(@"复制成功");
    }else{
        NSLog(@"复制失败");
    }
    BOOL isre= [manager removeItemAtPath:strPath error:nil];
    if (isre) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
    BOOL isMove = [manager moveItemAtPath:filePath toPath:strPath error:nil];
    if (isMove) {
        NSLog(@"移动成功");
    }else{
        NSLog(@"移动未成功");
    }
时间: 2024-08-26 04:18:16

初级数据持久化的相关文章

IOS 初级数据持久化-沙盒机制

什么是数据持久化?数据的永久存储 为什么要坐数据持久化:存储在内存中的数据,程序关闭,内存释放,数据丢失,这种数据是临时的 数据初九化的本质:数据保存成文件,存储到程序的沙河中 1.沙盒机制 每个应用程序位于文件系统的严格限制部分 每个应用程序只能在为该程序创建的文件系统中读取文件 每个应用程序在IOS系统内都放在了统一的文件夹目录下 沙盒的本质就是一个文件夹,名字是随机分配的. 2.沙盒路径的位置 1.通过Finder查找程序沙盒相对的路径 通过代码查找程序沙盒相对路径 NSString *D

初级数据持久化NSKeyedArchiver(二)

看代码: 1 #import "MainViewController.h" 2 #import "Student.h" 3 4 @interface MainViewController () 5 6 @end 7 8 @implementation MainViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 // Do any additional setup after loa

初级数据持久化(沙盒)

1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 // Do any additional setup after loading the view. 4 self.view.backgroundColor = [UIColor whiteColor]; 5 6 7 //沙盒:系统为每个应用程序分配的一个文件夹,文件夹名字随机,别人不能访问 8 9 NSString *sandBoxPath = NSHomeDirectory() ; 10 NSL

UI第十八讲.初级数据持久化

一.什么是沙盒机制 获取沙盒路径的方法: 1 //第一种 获取沙盒路径的方法 2 NSString *pathStr = NSUserName(); 3 NSString *homePathStr = NSHomeDirectoryForUser(pathStr); 4 NSLog(@"%@",homePathStr); 5 //第二种 获取沙盒路径的方法 6 NSString *homePathStr1 = NSHomeDirectory(); 7 NSLog(@"%@&q

hibernate载入持久化对象的两种方式——get、load

一.get与load对照 在hibernate中get和load方法是依据id取得持久化对象的两种方法.但在实际使用的过程中总会把两者混淆,不知道什么情况下使用get好,什么时候使用load方法效率更高.下边具体说一下get和load的不同,有些时候为了对照也会把find加进来. 1.从返回结果上对照: load方式检索不到的话会抛出org.hibernate.ObjectNotFoundException异常 get方法检索不到的话会返回null 2.从检索运行机制上对照: get方法和fin

Redis持久化存储

Redis介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点: Redis支持数据的持久化,可以将内存中的数据保持在磁盘中,重启的时候可以再次加载进行使用. Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储. Redis支持数据的备份,即master-slave模式的数据备份. Redis 优势 性能极高 – Redi

JMS开发步骤和持久化/非持久化Topic消息

------------------------------------------------ 开发一个JMS的基本步骤如下: 1.创建一个JMS connection factory 2.通过connection factory来创建JMS connection 3.启动JMS connection 4.通过connection创建JMS session 5.创建JMS destination 6.创建JMS producer 或者创建JMS message,并设置destination 7

【bzoj3674】 可持久化并查集加强版

http://www.lydsy.com/JudgeOnline/problem.php?id=3674 (题目链接) 题意 维护并查集3个操作:合并:回到完成第k个操作后的状态:查询. Solution 其实就是用主席树的叶子节点维护并查集的可持久化数组fa[]. 细节 终于认识到了按秩合并的强大,单纯写个路径压缩Re飞,写了路径压缩+按秩合并比单纯的按秩合并每快多少→_→ 代码 // bzoj3674 #include<algorithm> #include<iostream>

Redis持久化

Redis持久化功能简介: Redis为了内部数据的安全考虑,会把本身的数据以文件形式保存到硬盘中一份,在服务器重启之后会自动把硬盘的数据恢复到内存(redis)的里边. 数据保存到硬盘的过程就称为“持久化”效果. Redis持久化的两种方式:snap shotting  快照持久化  /  append only file   AOF持久化 snap shotting快照持久化 该持久化默认开启,一次性把redis中全部的数据保存一份存储在硬盘中,如果数据非常多(10-20G)就不适合频繁进行