ios資料存放區方式

來源:互聯網
上載者:User

標籤:

iOS應用資料存放區的常用方式

  1.xml屬性列表(plist)歸檔

  2. Preference(喜好設定)

  3.NSKeyedArchive歸檔(NSCoding)

  4.SQLite

  5.Core Data

  

1.xml屬性列表(plist)歸檔

"plist檔案儲存體"1.字串 數組 字典 可以直接儲存資料在一個檔案2.掌握沙箱備目錄的作用以及目錄路徑擷取方式// Document [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]// 緩衝 [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];// 臨時 NSTemporaryDirectory();// 主目錄  NSHomeDirectory();3.不是所有對象都可以儲存到plist檔案中,要有實現writeFile方法才可以4.學會使用SimPholders2開啟沙箱目錄

 

@interface HJPlistController ()@property (weak, nonatomic) IBOutlet UILabel *textView;@property (strong,nonatomic) NSString *docPath;- (IBAction)stringWrite:(id)sender;- (IBAction)stringRead:(id)sender;- (IBAction)arrayWrite:(id)sender;- (IBAction)arrayRead:(id)sender;- (IBAction)dictionoryWrite:(id)sender;- (IBAction)dictionaryRead:(id)sender;@end/** *  使用xml plist屬性列表歸檔 ,preference喜好設定,使用NSKeyedArchiver歸檔(NSCoding) */@implementation HJPlistController- (NSString *)docPath{    // 擷取 "沙箱"document目錄    if (_docPath == nil) {        _docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];        _docPath = [_docPath stringByAppendingPathComponent:@"data.plist"];    }    return _docPath;}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    // Do any additional setup after loading the view, typically from a nib.        //查看沙箱的路徑    //1.控制台列印沙箱的路徑,使用finder-前往-檔案夾 開啟    //2.控制台列印沙箱的路徑,開啟終端 open + 路徑    //3.使用simpholders工具    //4.可以斷點 輸入po NSHomeDirectory()        //擷取緩衝路徑(cache)//    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];//    NSLog(@"%@",cachePath);//    //    //    //擷取臨時路徑(tmp)//    NSString *tmpPath = NSTemporaryDirectory();//    NSLog(@"%@",tmpPath);//    //    //主目錄//    NSString *homePath = NSHomeDirectory();//    NSLog(@"%@",homePath);    }- (IBAction)stringWrite:(id)sender {    NSLog(@"%@",self.docPath);    NSString *data = @"ios中國";    [data writeToFile:self.docPath atomically:YES encoding:NSUTF8StringEncoding error:nil];}- (IBAction)stringRead:(id)sender {    NSString *resultStr = [NSString stringWithContentsOfFile:self.docPath encoding:NSUTF8StringEncoding error:nil];    self.textView.text = resultStr;}- (IBAction)arrayWrite:(id)sender{    NSArray *dataArray = [NSArray arrayWithObjects:@"a",@"b",@"c",@"中",@"國", nil];    [dataArray writeToFile:self.docPath atomically:YES];}- (IBAction)arrayRead:(id)sender{    NSArray *resultData = [NSArray arrayWithContentsOfFile:self.docPath];    NSMutableString *ms = [NSMutableString string];        for (NSString *str in resultData) {        [ms appendString:str];        [ms appendString:@"\n"];    }        self.textView.text = ms;}- (IBAction)dictionoryWrite:(id)sender{    NSDictionary *dict = @{@"a":@"1",@"2":@"2",@"zh":@"中國"};    [dict writeToFile:self.docPath atomically:YES];}- (IBAction)dictionaryRead:(id)sender{    NSDictionary *resultData = [NSDictionary dictionaryWithContentsOfFile:self.docPath];    NSMutableString *ms = [NSMutableString string];        NSArray *keys = resultData.allKeys;    for (NSString *key in keys) {        [ms appendFormat:@"%@:%@",key,resultData[key]];        [ms appendString:@"\n"];    }        self.textView.text = ms;}@end

 

2."使用者喜好設定"

"使用者喜好設定"1.ios中有個NSUserDefaults對象有可儲存資料,我們稱為使用者喜好設定2.通過[NSUserDefaults standardUserDefaults]可以擷取使用者喜好設定對象,儲存字串 布爾值 int等資料3.儲存資料時,一定要調用synchronize,因為資料要及時儲存到沙箱的檔案中/*  NSUserDefaults *defualts = [NSUserDefaults standardUserDefaults];    [defualts setObject:@"zhangsan" forKey:@"username"];  [defualts setObject:@"123" forKey:@"password"];  [defualts setBool:YES forKey:@"autoLogin"];  [defualts setBool:YES forKey:@"rememberPwd"];    //同步  [defualts synchronize];*/

4.掌握使用者喜好設定資料的擷取,更改,刪除

 

@interface HJPreferenceController ()@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;@property (weak, nonatomic) IBOutlet UISwitch *rememberSwith;@property (weak, nonatomic) IBOutlet UILabel *dataLabel;- (IBAction)saveBut:(id)sender;- (IBAction)readBut:(id)sender;- (IBAction)updateBut:(id)sender;- (IBAction)deleteBut:(id)sender;@end@implementation HJPreferenceController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {    // Get the new view controller using [segue destinationViewController].    // Pass the selected object to the new view controller.}*/- (IBAction)saveBut:(id)sender {    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];    [userDefault setObject:self.pwdTextField.text forKey:@"pwd"];    [userDefault setBool:self.rememberSwith.isOn forKey:@"isRememberPwd"];        // 同步資料    [userDefault synchronize];}- (IBAction)readBut:(id)sender {     NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];    self.dataLabel.text = [NSString stringWithFormat:@"%@:%@ %@:%d",@"pwd",[userDefault objectForKey:@"pwd"],@"isRememberPwd",[userDefault boolForKey:@"isRememberPwd"]];}// 修改喜好設定就是把索引值重寫設定 這樣會覆蓋原有的索引值- (IBAction)updateBut:(id)sender {    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];    [userDefault setObject:self.pwdTextField.text forKey:@"pwd"];    [userDefault setBool:self.rememberSwith.isOn forKey:@"isRememberPwd"];        [userDefault synchronize];        self.dataLabel.text = [NSString stringWithFormat:@"%@:%@ %@:%d",@"pwd",[userDefault objectForKey:@"pwd"],@"isRememberPwd",[userDefault boolForKey:@"isRememberPwd"]];        }- (IBAction)deleteBut:(id)sender {    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];        [userDefault removeObjectForKey:@"isRememberPwd"];        [userDefault synchronize];        self.dataLabel.text = [NSString stringWithFormat:@"%@:%@ %@:%d",@"pwd",[userDefault objectForKey:@"pwd"],@"isRememberPwd",[userDefault boolForKey:@"isRememberPwd"]];}@end

 

3.NSKeyedArchive歸檔(NSCoding)

"NSKeyedArchiver歸檔"/*什麼叫歸檔 歸檔就是把資料儲存到一個檔案中*/1.使用NSKeyedArchiver可以將NSArray NSDictiony NSString等對象歸檔到一個檔案2.只有實現了NSCoding協議的對象才可使用NSKeyedArchiver進行歸檔3.將模型對象儲存到一個檔案時,對象要遵守NSCoding協議,並實現NSKeyedArchiver的encodeWithCoder方法,4.從歸檔檔案裡讀取對象時要實現NSCoding的initWithCoder方法5.ios中,控制器,控制項都繼承NSCoding,storyboard/xib都是使用NSKeyedArchiver進行歸檔的

 

#import <Foundation/Foundation.h>@interface HJPerson : NSObject<NSCoding>@property (nonatomic,copy) NSString *name;@property (nonatomic,assign) int age;@property (nonatomic,strong) NSDate *birthday;@end
#import "HJPerson.h"@implementation HJPerson- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.name forKey:@"name"];    [aCoder encodeInt:self.age forKey:@"age"];    [aCoder encodeObject:self.birthday forKey:@"birthday"];}- (id)initWithCoder:(NSCoder *)aDecoder{    if (self == [super init]) {        self.name = [aDecoder decodeObjectForKey:@"name"];        self.age = [aDecoder decodeIntForKey:@"age"];        self.birthday = [aDecoder decodeObjectForKey:@"birthday"];    }    return self;}@end

 

#import "HJPerson.h"#warning 父類遵循了NSCoding方法就可以再此不遵循@interface HJStudent : HJPerson@property (nonatomic,strong) NSString *no;@end

#import "HJStudent.h"@implementation HJStudent- (void)encodeWithCoder:(NSCoder *)aCoder{#warning 記得在此調用父類的方法進行初始化    [super encodeWithCoder:aCoder];    [aCoder encodeObject:self.no forKey:@"no"];}- (id)initWithCoder:(NSCoder *)aDecoder{#warning 記得在此調用父類的方法進行初始化    if (self == [super initWithCoder:aDecoder]) {#warning 記得一定在此給屬性賦值操作        self.no = [aDecoder decodeObjectForKey:@"no"];    }    return self;}- (NSString *)description{    return [NSString stringWithFormat:@"%@,%d,%@,%@",self.name,self.age,self.birthday,self.no];}@end

 

////  HJCodingController.m//  資料存放區////  Created by HJiang on 14/12/30.//  Copyright (c) 2014年 HJiang. All rights reserved.//#import "HJCodingController.h"#import "HJStudent.h"@interface HJCodingController ()@property (strong,nonatomic) NSString *docPath;@property (weak, nonatomic) IBOutlet UITextField *nameTextField;@property (weak, nonatomic) IBOutlet UITextField *ageTextField;@property (weak, nonatomic) IBOutlet UITextField *noTextField;@property (weak, nonatomic) IBOutlet UITextField *birthdayTextField;@property (weak, nonatomic) IBOutlet UILabel *resultLabel;- (IBAction)birthdayChange:(UIDatePicker *)sender;- (IBAction)saveBut:(id)sender;- (IBAction)readBut:(id)sender;@end@implementation HJCodingController- (NSString *)docPath{    // 擷取 "沙箱"document目錄    if (_docPath == nil) {        _docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];        _docPath = [_docPath stringByAppendingPathComponent:@"data.archiver"];    }    return _docPath;}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {    // Get the new view controller using [segue destinationViewController].    // Pass the selected object to the new view controller.}*/- (IBAction)birthdayChange:(UIDatePicker *)sender {    NSDate *birthday = sender.date;    NSDateFormatter *df = [[NSDateFormatter alloc] init];    df.dateFormat = @"yyyy-MM-dd";    self.birthdayTextField.text = [df stringFromDate:birthday];    }- (IBAction)saveBut:(id)sender {    HJStudent *stu = [[HJStudent alloc] init];    stu.name = self.nameTextField.text;    stu.age = [self.ageTextField.text intValue];    NSDateFormatter *df = [[NSDateFormatter alloc] init];    df.dateFormat = @"yyyy-MM-dd";    stu.birthday = [df dateFromString:self.birthdayTextField.text];    stu.no = self.noTextField.text;        NSLog(@"%@",stu);        BOOL isSuccess = [NSKeyedArchiver archiveRootObject:stu toFile:self.docPath];    NSLog(@"%@",[email protected]"儲存成功":@"儲存失敗");    }- (IBAction)readBut:(id)sender {    NSLog(@"%@",self.docPath);    HJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:self.docPath];    NSLog(@"%@",stu);    self.resultLabel.text = [NSString stringWithFormat:@"%@,%d,%@,%@",stu.name,stu.age,stu.birthday,stu.no];}@end

 

ios資料存放區方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.