1 //获取home目录 2 NSString *homePath = NSHomeDirectory(); 3 NSLog(@"home%@",homePath); 4 5 //获取documents目录 6 //方式1: 7 NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 8 NSString *documentsPath = [documents lastObject]; 9 NSLog(@"%@",documentsPath); 10 //方式2:拼接字符串 11 NSString *documentPath2 = [homePath stringByAppendingPathComponent:@"Documents"]; 12 NSLog(@"documenPath2:%@",documentPath2); 13 14 //获取caches缓存目录 15 NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 16 NSString *cachesPath = [caches lastObject]; 17 NSLog(@"cachesPath:%@",cachesPath); 18 19 //获取临时目录 20 NSString *tmp = NSTemporaryDirectory(); 21 NSLog(@"tmp:%@",tmp); 22 23 //在documents目录下创建文件 24 NSFileManager *fm = [NSFileManager defaultManager]; 25 NSString *fileName = [documentsPath stringByAppendingPathComponent:@"1.txt"]; 26 NSString *str = @"hello world"; 27 NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; 28 29 if ([fm createFileAtPath:fileName contents:data attributes:nil]) { 30 NSLog(@"file create successful"); 31 } 32 33 //读出文件的内容 34 NSError *error = nil; 35 36 NSString *str2 = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:&error]; 37 if (!error) { 38 NSLog(@"str2:%@",str2); 39 } 40 else 41 { 42 NSLog(@"%@",error); 43 } 44 //NSBundle对象:图片、xib、storyBoard、plist文件都是放在应用程序包中 45 NSBundle *bundle = [NSBundle mainBundle]; 46 //获取包中文件的路径; 47 NSString *path = [bundle pathForResource:@"array" ofType:@"plist"]; 48 //加载包中的xib文件 49 NSArray *views = [bundle loadNibNamed:@"cell" owner:self options:nil];
二、Preference(用户偏好设置)
很多iOS应⽤用都⽀持偏好设置,⽐如保存⽤户名、密码、字体⼤小等设置, iOS提供了⼀套标准的解决⽅案来为应用加⼊偏好设置功能每个应⽤都有个NSUserDefaults实例,通过它来存取偏好设置。
1)偏好设置是专门用来保存应用程序的配置信息的, 一般情况不要在偏好设置中保存其他数据。如果利用系统的偏好设置来存储数据, 默认就是存储在Preferences文件夹下面的,偏好设置会将所有的数据都保存到同一个文件中。
2)使用偏好设置对数据进行保存之后, 它保存到系统的时间是不确定的,会在将来某一时间点自动将数据保存到Preferences文件夹下面,如果需要即刻将数据存储,可以使用[defaults synchronize];
3)注意点:所有的信息都写在一个文件中,对比简单的plist可以保存和读取基本的数据类型。
4)步骤:获取NSuserDefaults,保存(读取)数据
代码参考如下:
创建用户偏好设置,保存信息 #import "AppDelegate.h" ...... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //创建用户偏好设置对象 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:@"admin" forKey:@"userName"]; [userDefaults setObject:@"123456" forKey:@"userPassword"]; [userDefaults setInteger:2 forKey:@"loginTime"]; [userDefaults setObject: [NSDate date] forKey:@"loginDate"]; //同步保存 [userDefaults synchronize]; NSLog(@"%@",NSHomeDirectory()); return YES; } ...... //创建偏好设置,读取信息(注意:NSUserDefaults是单例对象) #import "ViewController.h" ...... - (void)viewDidLoad { [super viewDidLoad]; NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; NSString *userName = [userDefault objectForKey:@"userName"]; NSString *userPassword = [userDefault objectForKey:@"userPassword"]; NSInteger loginTime = [userDefault integerForKey:@"loginTime"]; NSDate *loginDate = [userDefault objectForKey:@"loginDate"]; NSDateFormatter *df = [[NSDateFormatter alloc]init]; NSString *Date = [df stringFromDate:loginDate]; NSLog(@"%@,%@,%ld,%@",userName,userPassword,loginTime,loginDate); } ......
注意:UserDefaults设置数据时,不是立即写入,而是根据时间戳定时地把缓存中的数据写⼊本地磁盘。所以调⽤了set方法之后数据有可能还没有写入磁盘应用程序就终止了。出现以上问题,可以通过调⽤synchornize方法强制写入。
三、NSKeyedArchiver(归档)
1.如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,可以直接⽤用NSKeyedArchiver进⾏行归档和恢复
//创建需要归档的对象数据 NSArray *array = @[@1,@2,@4,@3]; //创建拼接路径 NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [documents lastObject]; NSString *archiverPath = [path stringByAppendingPathComponent:@"archiver.arc"]; //执行归档操作 if ([NSKeyedArchiver archiveRootObject:array toFile:archiverPath]) { NSLog(@"归档成功"); } else { NSLog(@"归档失败"); } //打印Home目录 NSLog(@"%@",NSHomeDirectory()); //解归档操作 NSArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath]; NSLog(@"%@",array2);
2.不是所有的对象都可以直接用这种方法进行归档,只有遵守了NSCoding协议的对象才可以, NSCoding协议有2个⽅方法: 实例变量,可以使用encodeObject:forKey:⽅法归档实例变量
◆ initWithCoder :
每次从⽂件中恢复(解码)对象时,都会调⽤这个方法。⼀般在这个⽅法⾥面指定如何解码文件中的数据为对象的实例变量,可以使用decodeObject:forKey⽅法解码实例变量
◆ encodeWithCoder :
每次归档对象时,都会调⽤这个方法。⼀般在这个⽅法⾥面指定如何归档对象中的每个实例变量
代码如下:
ViewController.m文件代码如下:
#import "ViewController.h" #import "Person.h" ...... [super viewDidLoad]; Person *person = [[Person alloc]init]; person.name = @"zhangsan"; person.age = 22; person.gender = 'F'; //拼接保存路径 NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [documents lastObject]; NSString *archiverPath = [path stringByAppendingPathComponent:@"archiver.arc"]; //执行归档操作 if ([NSKeyedArchiver archiveRootObject:person toFile:archiverPath]) { NSLog(@"归档成功"); } else { NSLog(@"归档失败"); } NSLog(@"%@",NSHomeDirectory()); //解归档,创建新的对象 Person *person2 = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath]; NSLog(@"%@",person2); .....
Person.m代码如下:
#import "Person.h" @implementation Person -(instancetype)initWithName:(NSString *)name andAge:(NSInteger)age andGender:(char)gender { if (self = [super init]) { _name = [name copy]; _age = age; _gender = gender; } return self; } -(NSString *)description { return [NSString stringWithFormat:@"name:%@,age:%ld,gender:%c",_name,_age,_gender]; } -(void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeInteger:self.age forKey:@"age"]; [aCoder encodeInteger:self.gender forKey:@"gender"]; } -(id)initWithCoder:(NSCoder *)aDecoder { self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; self.gender = [aDecoder decodeIntegerForKey:@"gender"]; return self; } @end
NSKeyedArchiver-归档对象的注意如果⽗类也遵守了NSCoding协议,请注意:
应该在encodeWithCoder:⽅法中加上⼀一句 [super encodeWithCode:encode];
确保继承的实例变量也能被编码,即也能被归档
应该在initWithCoder:⽅法中加上⼀一句 self = [super initWithCoder:decoder];
确保继承的实例变量也能被解码,即也能被恢复
3.NSData进行多个对象归档
NSString *userName = @"zhangsan"; NSInteger age = 22; NSString *address = @"北京尚学堂"; //创建一个可变数据区,用于保存对象 NSMutableData *data = [[NSMutableData alloc]init]; //拼接路径 NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [documents lastObject]; NSString *archiverPath = [path stringByAppendingPathComponent:@"archiver.arc"]; //创建归档对象,将要归档的对象加入data可变数据区中 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; //归档操作 [archiver encodeObject:userName forKey:@"name"]; [archiver encodeInteger:age forKey:@"age"]; [archiver encodeObject:address forKey:@"address"]; //结束归档 [archiver finishEncoding]; //将data的数据写入到文件中,保存起来。 [data writeToFile:archiverPath atomically:YES]; //创建新的可变数据区 NSMutableData *data2 = [NSMutableData dataWithContentsOfFile:archiverPath]; //解归档操作 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data2]; NSString *name = [unarchiver decodeObjectForKey:@"name" ]; NSInteger age2 = [unarchiver decodeIntegerForKey:@"age"]; NSString *address2 = [unarchiver decodeObjectForKey:@"address"]; NSLog(@"name:%@,age:%ld,address:%@",name,age2,address2);