博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
初级数据持久化
阅读量:7014 次
发布时间:2019-06-28

本文共 6068 字,大约阅读时间需要 20 分钟。

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
遵循协议@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(@"移动未成功");    }

 

转载于:https://www.cnblogs.com/gsdxinxin/p/4482969.html

你可能感兴趣的文章