Day-04

第一节 NSUserDefaults(偏好设置的存取)

1.NSUserDefaults了解
2.NSUserDefaults用法

1>  存:
   NSUserDefaults*userSave = [NSUserDefaultsstandardUserDefaults]; 
    [userSave setObject:@"value"forKey:@"valueKey"];
    [userSave setBool:YESforKey:@"boolKey"];
    [userSave synchronize];
2>取
NSUserDefaults*userRaead = [NSUserDefaultsstandardUserDefaults];
NSString*value = [userRaead objectForKey:@"valueKey"];
BOOLisBool = [userRaead boolForKey:@"boolKey"];

第二节 plist文件存储

1>  存
    //获取沙盒路径
    NSString *homePath = NSHomeDirectory();
    NSLog(@"%@",homePath);
    NSArray *dataArray = [NSArray arrayWithObjects:@"123", @"abc",nil];
    //获取存储文件Caches路径参数1directory:要搜索的文件夹 参数2domainMask:在哪个范围搜索 参数3expandTilde:是否需要展开路径
    NSString *cachesPath =   NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0];
    //拼接文件名
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"app.plist"];
    //写入文件 参数File:文件路径
    [dataArray writeToFile:filePath atomically:YES];
2>  取
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"app.plist"];
NSArray *dataArray = [NSArray arrayWithContentsOfFile:filePath];

第三节 归档/解档

1.归档、解档步骤
1> 创建要归档对象
2> 遵守NSCoding协议
3> 实现协议方法
4> 进行归档,解档

1>  对象.h文件
#import 
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject
@property (nonatomic,assign) int age;
@property (nonatomic,strong) NSString *name;
//告诉系统哪些属性需要归档
-(void)encodeWithCoder:(NSCoder *)aCoder;
//告诉系统哪些属性需要解档
-(instancetype)initWithCoder:(NSCoder *)aDecoder;
@end
NS_ASSUME_NONNULL_END
2>  对象.m文件
#import "Person.h"
@implementation Person
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInt:_age forKey:@"age"];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        _age = [aDecoder decodeIntForKey:@"age"];
        _name = [aDecoder decodeObjectForKey:@"name"];
    }
    return self;
}
@end
1>    归档

    Person*p = [[Personalloc] init];
    p.age= 18;
    p.name= @"Jack";
   //归档(任何对象都可以一般用作自定义对象)获取caches文件夹
   NSString*cachesFile =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
   //拼接文件名
   NSString*filePath = [cachesFile stringByAppendingString:@"peson.data"];
   //参数Object:要归档的对象File文件全路径
  [NSKeyedArchiverarchiveRootObject:p toFile:filePath];   
2>  解档
   //解档
   NSString*cachesFile =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString*filePath = [cachesFile stringByAppendingString:@"peson.data"];
    Person*p = [NSKeyedUnarchiverunarchiveObjectWithFile:filePath];
    NSLog(@"%d   %@",p.age,p.name);

你可能感兴趣的:(Day-04)