IOS開發—資料存放區(直接寫入、NSUserDefaults、NSkeyedArchiver)

來源:互聯網
上載者:User

IOS開發—資料存放區(直接寫入、NSUserDefaults、NSkeyedArchiver)
資料存放區(直接寫入、NSUserDefaults、NSkeyedArchiver)
ios中熱門檔案存取的方法有:

1、直接寫檔案的方式,可以儲存的對象有NSString、NSArray、NSDictionary、NSData、NSNumber,資料全部存放在一個屬性列表檔案(*.plist檔案)中。

2、NSUeserDefaults(喜好設定),用來儲存應用設定資訊,檔案放在perference目錄下。

3、歸檔操作(NSkeyedArchiver),不同於前面兩種,它可以把自訂對象存放在檔案中。

 

首先每個開發人員都應該知道,對於一個應用來說,有唯一的沙箱與之對應,即每個應用不能跨沙箱操作檔案。

一、擷取沙箱路徑,通過寫檔案的方式儲存資料

直接來看代碼:

 

#import "ViewController.h"@interface ViewController ()@end@implementationViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view,typically from a nib.    [self mainOperation];}- (void)mainOperation{    //擷取沙箱中快取檔案夾路徑    //方法一    //沙箱主目錄    NSString *homePath = NSHomeDirectory();    //拼接路徑    NSString *path = [homePath stringByAppendingPathComponent:@"Library/Caches"];       //方法二    //第一個參數目標檔案夾目錄(NSCachesDirectory尋找快取檔案夾),第二個參數為尋找目錄的域(NSUserDomainMask為在使用者目錄下尋找),第三個參數為結果中主目錄是否展開,不展開則顯示為~    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    //雖然該方法返回的是一個數組,但是由於一個目標檔案夾只有一個目錄,所以數組中只有一個元素。    NSString *cachePath = [arr lastObject];    //或者//    NSString *cachePath = [arr objectAtIndex:0];  /**    //擷取沙箱中Document檔案夾或者tmp檔案夾路徑都可使用上面兩種方法    //tmp檔案夾路徑可直接這樣擷取    NSString *tmpPath = NSTemporaryDirectory();    NSLog(@"%@",tmpPath);**/       //拼接路徑(目標路徑),這個時候如果目錄下不存在這個lotheve.plist檔案,這個目錄實際上是不存在的。    NSString *filePath = [cachePath stringByAppendingPathComponent:@"tese.plist"];    NSLog(@"%@",filePath);       //建立資料    NSDictionary *content = @{@"字典資料測試1":@"1",@"字典資料測試2":@"2",@"字典資料測試":@"3"};    //將資料存到目標路徑的檔案中(這個時候如果該路徑下檔案不存在將會自動建立)    //用writeToFile方法寫檔案會覆蓋掉原來的內容    [content writeToFile:filePath atomically:YES];      //讀取資料(通過字典的方式讀出檔案中的內容)    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];    NSLog(@"%@",dic);}@end

沙箱中Library/Caches目錄下多了lotheve.plist檔案

檔案內容:

二、使用NSUeserDefaults(喜好設定)實現資料存放區

每個應用都有一個NSUesrDefaults執行個體,通過它可以儲存應用配置資訊以及使用者資訊,比如儲存使用者名稱、密碼、字型大小、是否自動登入等等。資料自動儲存在沙箱的Libarary/ Preferences目錄下。同樣,該方法只能存取NSString、NSArray、NSDictionary、NSData、NSNumber類型的資料。

程式碼範例:

 

#import "LXXViewController.h"@interface LXXViewController ()@end@implementationLXXViewController- (void)viewDidLoad{    [super viewDidLoad];    self.title = @"NSUserDefaults Demo";}//點擊button儲存資料- (IBAction)saveData:(id)sender {    //擷取NSUserDefaults對象    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];    //存資料,不需要設定路勁,NSUserDefaults將資料儲存在preferences目錄下    [userDefaults setObject:@"Lotheve" forKey:@"name"];    [userDefaults setObject:@"NSUserDefaults" forKey:@"demo"];    //立刻儲存(同步)資料(如果不寫這句話,會在將來某個時間點自動將資料儲存在preferences目錄下)    [userDefaults synchronize];    NSLog(@"資料已儲存");}//點擊button讀取資料- (IBAction)getData:(id)sender{    //擷取NSUserDefaults對象    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];    //讀取資料    NSString *name  = [userDefaults objectForKey:@"name"];    NSString *demo = [userDefaults objectForKey:@"demo"];    //列印資料    NSLog(@"name = %@ demo =%@",name,demo);}@end

 

Interface Building中設定了兩個按鈕:

點擊“儲存資料”後,查看沙箱中的Libarary/ Preferences目錄:

 

資料以plist的格式寫入磁碟中了。點開查看資料:

 

三、NSKeyedArchiver(歸檔操作)

使用歸檔操作儲存資料的主要好處是,不同於前面兩種方法只能儲存幾個常用的資料類型的資料,NSKeyedArchiver可以儲存自訂的對象。

程式碼範例:

需要注意的是,需要儲存的對象類一定要引用NSCoding協議,並且實現

 

- (void)encodeWithCoder:(NSCoder *)aCoder- (id)initWithCoder:(NSCoder *)aDecoder   

1、檔案結構:

2、程式碼範例:

LXXViewController.m

 

#import "LXXViewController.h"#import "TestPerson.h"@interface LXXViewController ()@property (nonatomic ,strong) TestPerson *p;@end@implementationLXXViewController - (void)viewDidLoad {    [super viewDidLoad];}- (IBAction)saveData:(id)sender{    //建立一個自訂類的執行個體    _p = [[TestPerson alloc]init];    _p.name = @"Lotheve";    _p.age = 20;    _p.sex = @"m";    _p.familyMumbers = @[@"Father",@"Mather",@"Me"];       //擷取檔案路徑    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    //檔案類型可以隨便取,不一定要正確的格式    NSString *targetPath = [docPath stringByAppendingPathComponent:@"lotheve.plist"];      //將自訂對象儲存在指定路徑下    [NSKeyedArchiver archiveRootObject:_p toFile:targetPath];    NSLog(@"檔案已儲存");}

 

- (IBAction)getData:(id)sender{    //擷取檔案路徑    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSString *targetPath = [docPath stringByAppendingPathComponent:@"lotheve.plist"];       TestPerson *person = [NSKeyedUnarchiver unarchiveObjectWithFile:targetPath];    NSLog(@"name = %@ , age =%ld , sex = %@ , familyMubers = %@",person.name,person.age,person.sex,person.familyMumbers);    NSLog(@"檔案已提取");}@end

 

TestPerson.h

 

#import @interface TestPerson : UIViewController@property (nonatomic, copy) NSString *name;@property (nonatomic, assign) NSInteger age;@property (nonatomic, copy) NSString *sex;@property (nonatomic, strong) NSArray *familyMumbers;@end

 

TestPerson.m

 

#import "TestPerson.h"@interface TestPerson ()@end@implementationTestPerson- (void)viewDidLoad{    [super viewDidLoad];}#pragma mark - NSCoding協議方法 (一定要實現)//當進行歸檔操作的時候就會調用該方法//在該方法中要寫清楚要儲存物件的哪些屬性- (void)encodeWithCoder:(NSCoder *)aCoder{    NSLog(@"調用了encodeWithCoder方法");    [aCoder encodeObject:_name forKey:@"name"];    [aCoder encodeInteger:_age forKey:@"age"];    [aCoder encodeObject:_sex forKey:@"sex"];    [aCoder encodeObject:_familyMumbers forKey:@"familyMumbers"];} //當進行解檔操作的時候就會調用該方法//在該方法中要寫清楚要提取對象的哪些屬性- (id)initWithCoder:(NSCoder *)aDecoder{    NSLog(@"調用了initWithCoder方法");    if (self = [super init]) {        self.name = [aDecoder decodeObjectForKey:@"name"];        self.age = [aDecoder decodeIntegerForKey:@"age"];        self.sex = [aDecoder decodeObjectForKey:@"sex"];        _familyMumbers = [aDecoder decodeObjectForKey:@"familyMumbers"];    }    return self;}@end

點擊“儲存資料”後,查看沙箱中Documents目錄:

 

點擊查看檔案內容:

 

點擊“提取資料”後列印結果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.