objective-C 沙盒存储

沙盒存储——plist


objective-C 沙盒存储_第1张图片
1111.png

属性列表是一种XML格式的文件,拓展名为plist。如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件中

如果是其他类型的的对象,需要使用plist储存,需要转类型:
例如://转化Data
NSData * imageData = UIImagePNGRepresentation(getImage);

存:

//获取路径
// NSSearchPath寻找路径
// ForDirectories要找的文件夹
// InDomains在哪个地方找
// NSDocumentDirectory Documents

NSString *docPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
//拼接路径   
NSString *filePath = [docPath stringByAppendingPathComponent:@"xxxx.plist"];
 
//创建字典
NSDictionary *dict =@{@"name":@"laoma",@"age":@"18"};

// 存储字典
[dict writeToFile:filePath atomically:YES];

取:

   //获取doc路径   
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
//拼接plist路径   
NSString *filePath = [docPath stringByAppendingPathComponent:@"xxxx.plist"];      
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];   

NSLog(@"%@",dict[@"name"]);

字符串存取

- (IBAction)save:(id)sender {
   //获取docpath
   NSString *docpath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];

   //拼接路径
   NSString *filepath = [docpath stringByAppendingPathComponent:@"x.plist"];

   NSString *str =@“hello word"
;
   [str writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (IBAction)read:(id)sender {

   //获取docpath   
NSString *docpath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];     
//拼接路径   
NSString *filepath = [docpath stringByAppendingPathComponent:@"x.plist"];   
   // 获取字符串
NSString *str = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",str);
}


沙盒储存——归档解档

#import
@interface Person :NSObject
@property(nonatomic,copy)NSString *name;

@property(nonatomic,assign)NSInteger age;
@end
#import"Person.h"
@implementationPerson

//告诉系统归档哪些属性
- (void)encodeWithCoder:(NSCoder *)aCoder {      
  [aCoder encodeObject:_name forKey:@"name"]; 
  [aCoder encodeInteger:_age forKey:@"age"];
}
//告诉系统解档哪些属性,如何解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  if(self= [super init]) { 
    _name= [aDecoder decodeObjectForKey:@"name"]; 
    _age= [aDecoder decodeIntegerForKey:@"age"];    
  }   
  return self;
}
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController()
@end
@implementation ViewController
//归档
- (IBAction)save:(id)sender {      
//创建对象   
Personn*p = [[Person alloc]init];       
p.name=@"zhangsan";    
p.age=18;      
// docpath   
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
// 拼接路径   
NSString *fliePath = [docPath stringByAppendingPathComponent:@"person.data"];      
//归档    
[NSKeyedArchiver archiveRootObject:p toFile:fliePath];   
}


//解档
- (IBAction)read:(id)sender {      
// docpath   
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
// 拼接路径   
NSString *fliePath = [docPath stringByAppendingPathComponent:@"person.data"];      
//解档   
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:fliePath];      
NSLog(@"%@",p.name);
}

- (void)viewDidLoad {    
[super viewDidLoad];   
// Do any additional setup after loading the view, typically from a nib.}
- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];   
// Dispose of any resources that can be recreated.}
@end


沙盒存储——偏好设置userDefaults

保存设置

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:@"itcast"  forKey:@"username"];

[defaults setFloat:18.0f  forKey:@"text_size"];

[defaults setBool:YES  forKey:@"auto_login"];

读取上次保存的设置

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *username = [defaults stringForKey:@"username"];
float textSize = [defaults floatForKey:@"text_size"];
BOOL autoLogin = [defaults boolForKey:@"auto_login"];

注意:UserDefaults设置数据时,不是立即写入,而是根据时间戳定时地把缓存中的数据写入本地磁盘。所以调用了set方法之后数据有可能还没有写入磁盘应用程序就终止了。出现以上问题,可以通过调用synchornize方法强制写入

[defaults synchornize];

你可能感兴趣的:(objective-C 沙盒存储)