IOS学习笔记-ios中的文件目录和XML文件

IOS中的每个应用都有自己的特定目录来保存文件和各类信息,且无法访问其他应用的目录或文件。这种沙盒机制,可以有效防止恶意软件或者病毒的侵袭。

在IOS中,应用将文件保存在"Documents"目录中,且这个目录将永远保存在应用的沙盒之中。当用户使用ITunes或iCloud备份时,Documents文件中的文件也会被备份。当开发者发布了一个新版本时,用户会安装更新内容,但是Documents文件夹却依然完好无损,因此任何保存在该文件中的数据不会被删除。

//获得Documents文件夹的完整路径

- (NSString *)documentsDirectory{

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

NSString *documentsDirectory = [paths firstObject];

return documentsDirectory;

}


//获得名称为"XXX.xxx"的文件的完整路径

- (NSString *)dataFilePath{

return [[self documentsDirectory] stringByAppendingPathComponent:@"XXX.xxx"];

}

或者

- (NSString *)dataFilePath{

return [NSString stringWithFormat:@"%@/XXX.xxx",[self documentsDirectory]];

}


在任何一个IOS应用中,都有一个Info.plist文件。它是一个XML文件,用来保存该应用的相关设置。为了保存.plist文件,需要用到NSCoder系统,使用它可以让对象用结构化的文件格式来保存数据。保存数据,需要进行encoding编码;读取数据,需要进行decoding解码。

以将一个_items数组保存到.plist文件中为例,代码如下:

- (void)saveItems{

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

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

[archiver encodeObject:_items forKey:@"Items"];

[archiver finishEncoding];

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

}

上述函数首先将items数组中的内容转换为二进制数据块,然后把数据块写入到文件中:

1.NSKeyedArchiver,用于创建.plist文件的NSCoder的一种形式,它可以对数组进行编码,然后讲所有的数据写入到某种二进制数据格式中。

2.数据会被保存到一个NSMutableData对象中,它可以将自身写入到通过dataFilePath所获得的完整路径的文件中。

将这个函数应用到需要保存数据的位置,在_items数组中的数据发生变化时,将改变后的_items数组保存到.plist文件中。

但是还需要对_items数组中的每个对象进行编码,即让对象遵从NSCoding协议,并且实现该协议的方法。

encodeWithCode方法编码:

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

[aCoder encoderObject:self.text forKey:@"Text"];

[aCoder encoderBool:self.checked forKey:@"Checked"];

}

initWithCoder方法解码:

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

if(self = [super init]){

self.text = [aDecoder decodeObjectForKey:@"Text"];

self.checked = [aDecoder decodeBoolForKey:@"Checked"];

}

return self;

}


在读取数组数据的文件中添加以下方法:

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

if(self = [super initWithCoder:aDecoder]){

[self loadChecklistItems];

}

return self;

}


- (void)loadChecklistItems{

NSString *path = [self dataFilePath];

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

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

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

_items = [unarchiver decodeObjectForKey:@"ChecklistItems"];

[unarchiver finishDecoding];

}

else{

_items = [[NSMutableArray alloc] initWithCapacity:20];

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值