ios 开发学习日志    沙盒机制数据持久化

 

1.plist 文件
NSArray,NSDictionayr,NSString,NSData;
witreContentToFile
arrayWithContentOfFile
只能存储OC内置的对象
2.归档
自定义对象可以使用归档存储
遵循NSCoding协议
实现两个方法:
initWithCoder\ encodeWithCoder
两个对象:
NSKeyedArchive\ NSKeyedUnarchive
3.偏好设置
4.SQLite3嵌入式关系数据库 
FMDB 第三方数据库
5.coreData 对象数据库

    // 获取home目录

    NSString *home=NSHomeDirectory();

    NSLog(@"home:%@",home);

    // 获取document目录

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *document=[paths lastObject];

    NSLog(@"document:%@",document);

    // 获取Cache目录

    NSArray *caches=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);

    NSString *cache=caches[0];

    // 获取Preferences目录

通过NSUserDefaults类存取该目录下的设置信息

 // 获取Tmp目录

    NSString *temDir=NSTemporaryDirectory();


   二. 编码和解码   

 1. 获取程序存储目录

-(NSString *)documentsDirectory{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *documentsDirectory=[paths lastObject];

    return documentsDirectory;

}

-(NSString *)dataFilePath{

    return [[self documentsDirectory] stringByAppendingPathComponent:@" "];

}

2.编码

-(void)saveList{

    NSMutableData *data=[[NSMutableData alloc]init];

    NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:self.__ forKey:@"__"];

    [archiver finishEncoding];

    [data writeToFile:[self dataFilePath] atomically:YES];

 

}

 

 3.NSKeyedArchiver不仅需要知道如何对数组编码,还需要知道如何对每个数组中的对象进行编码

  在对象的类中,添加协议,实现encodeWithCoder方法

-(void)encodeWithCoder:(NSCoder *)aCoder{

[aCoder encodeObject:self.__ forkey @"__"];

}

 3.解码

-(id)initWithCoder:(NSCoder *)aDecoder{

if ((self=[super init])){

self.__=[aDecoder decodeObjectForKey:@"Name"];

}

return self;

}

3.plist文件

-(void)loadList{

    NSString *path=[self dataFilePath];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {

        NSData *data=[[NSData alloc] initWithContentsOfFile:path];

        NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];

        self.lists=[unarchiver decodeObjectForKey:@"__"];

        [unarchiver finishDecoding];

 

    }else {

        self.lists=[[NSMutableArray alloc] initWithCapacity:50];

    }

}

   首先,我们将[self dataFilePath]返回的结果(也就是沙盒应用)保存在一个名为path的临时变量中,接下来我们确认沙盒中是否存在该文件,如果没有就创建一个空的NSMutablearray,当应用从沙盒中找到.plist文件时,我们无需创建一个新的数组,此时我们可以从.plist文件中加载整个数组和其中的内容,现在可以取出viewDidLoad中的伪数据

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值