objective-C 沙盒存儲

沙盒存儲——plist


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<Foundation/Foundation.h>
@interface Person :NSObject<NSCoding>
@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];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容