1.plist 文件
// 获取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中的伪数据