iOS資料持久化(一),ios資料

來源:互聯網
上載者:User

iOS資料持久化(一),ios資料

一、什麼是資料持久化

資料持久化及資料的永久儲存,將資料儲存在硬碟中,程式關閉,記憶體釋放後,重新開啟程式,可以繼續訪問之前儲存的資料。

二、資料持久化方式

常見的資料持久化方式有以下幾項:

沙箱

preference

歸檔 / 反歸檔

SQLite

CoreData

這篇只講沙箱,preference,歸檔/反歸檔。

1.沙箱

沙箱是系統為每一個應用程式產生的一個特定檔案夾   檔案夾的名字由十六進位資料群組成,每一個應用程式的沙箱檔案名稱都是不一樣的,是由系統隨機產生的。

    //擷取沙箱主目錄    NSString *path = NSHomeDirectory();    NSLog(@"%@",path);

沙箱下每個檔案夾的路徑及作用

//Documents  存放的一些比較重要的檔案,但是存入Documents中的檔案不能過大    //如何擷取Documents檔案目錄    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];    NSLog(@"%@",documentsPath);    //用firstobject取值是因為該方法一開始使用mac端OS X開發,對於PC端使用者可以有多個使用者,所以可以取到很多user的路徑,但是該方法現在用於手機開發,手機端只有一個使用者,所以獲得的使用者只有一個,lastobject也是可以的。        //Library:是一個資產庫,儲存一些不太重要的資料,相對比較大一些,裡邊有兩個子檔案夾;    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];    //Caches:快取檔案,圖片緩衝,音頻,視頻。網頁資源。應用程式清除緩衝,就是清除該檔案夾    NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];    //Preferences:系統喜好設定,使用者對應程式的設定,比如使用者名稱和使用者密碼,preference路徑無法找到,通過NSUserDefaults        //temp:存放臨時檔案,比如下載的壓縮包zip,解壓後理解把壓縮包刪除    NSString *tempPath = NSTemporaryDirectory();    NSLog(@"%@",tempPath);    //bundle:ios8之前,包和沙河在同一個目錄下,之後.app單獨儲存到一個獨立的檔案目錄下。 .app 檔案 readOnly。從appStore下載下來的是這個包,程式上傳的時候也是這個包    NSString *bundlepath = [[NSBundle mainBundle] bundlePath];    NSLog(@"%@",bundlepath);
    // NSSearchPathDirectory 這個類是用來尋找檔案目錄的    //第一個參數:檔案名稱    //第二個參數,確定搜尋域    //第三個參數:確定相對路徑還是絕對路徑。YES絕對,NO相對

檔案相關操作

/** *  檔案刪除 */- (void)deleteFile {    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];     NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"iamge"];    NSLog(@"%@",imagePath);    //建立檔案管理者    NSFileManager *fileManager =  [NSFileManager defaultManager];    //判斷檔案是否存在    BOOL isExist = [fileManager fileExistsAtPath:imagePath];    if (!isExist) {        BOOL isSuccess = [fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];        NSLog(@"%@",isSuccess ? @"建立成功" : @"建立失敗");    }    //刪除檔案    if ([fileManager fileExistsAtPath:imagePath]) {        BOOL isSucess = [fileManager removeItemAtPath:imagePath error:nil];        NSLog(@"%@",isSucess ? @"刪除成功" : @"刪除失敗");    }}
/** *  移動 */- (void)moveFile {    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];        NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"iamge"];    NSLog(@"%@",imagePath);    //建立檔案管理者    NSFileManager *fileManager =  [NSFileManager defaultManager];    //判斷檔案是否存在    BOOL isExist = [fileManager fileExistsAtPath:imagePath];    if (!isExist) {        BOOL isSuccess = [fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];        NSLog(@"%@",isSuccess ? @"建立成功" : @"建立失敗");    }    //刪除檔案    //    if ([fileManager fileExistsAtPath:imagePath]) {    //        BOOL isSucess = [fileManager removeItemAtPath:imagePath error:nil];    //        NSLog(@"%@",isSucess ? @"刪除成功" : @"刪除失敗");    //    }    //拷貝檔案    //    把包中的plist檔案拷貝到image檔案夾下    NSString *plistInBundlePath = [[NSBundle mainBundle] pathForResource:@"NB.plist" ofType:nil];        NSString *nBPath = [imagePath stringByAppendingPathComponent:@"NB.plist"];    // 拷貝,    if (![fileManager fileExistsAtPath:nBPath]) {        BOOL isSuccess = [fileManager copyItemAtPath:plistInBundlePath toPath:nBPath error:nil];        NSLog(@"%@",isSuccess ? @"拷貝成功" : @"拷貝失敗");    }        NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];    BOOL isSuccess = [fileManager moveItemAtPath:nBPath toPath:[toPath stringByAppendingPathComponent:@"NB.plist"] error:nil];    NSLog(@"%@",isSuccess ? @"移動成功" : @"移動失敗");    }
//字串寫入檔案- (void)writeToFile {    //簡單對象寫入檔案:字串,數組,字典,二進位流 只有這些簡單對象支援檔案的寫入    //如果要寫入的檔案資料時數組,字典,必須要保證數組,字典中的資料 也是簡單對象(如果是複雜物件,請參照後邊的歸檔,反歸檔)    //將字串寫入Documents檔案夾下    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];    NSString *toPath = [documentsPath stringByAppendingPathComponent:@"string.txt"];    NSString *string = @"string-string-string-";    //第一個參數,要寫入的檔案路徑,如果不存在檔案,會自動建立    第二個參數,原子性,判斷是否需要產生輔助檔案,保護在多線程下安全    第三個參數,編碼格式    第四個參數,錯誤資訊    NSError *error = nil;    BOOL isSuccess = [string writeToFile:toPath atomically:YES encoding:NSUTF8StringEncoding error:&error];    NSLog(@"%@",isSuccess ? @"寫入成功" : @"寫入失敗");        NSString *str = [NSString stringWithContentsOfFile:toPath encoding:NSUTF8StringEncoding error:nil];    NSLog(@"%@",str);}
//數組寫入檔案- (void)writeArray {        NSString *str = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];    NSString *toPath = [str stringByAppendingPathComponent:@"array.txt"];    NSArray *array = @[@"123",@"123"];    BOOL isSuccess = [array writeToFile:toPath atomically:YES];    NSLog(@"%@",isSuccess ? @"寫入成功" : @"寫入失敗");        NSArray *arr = [NSArray arrayWithContentsOfFile:toPath];    NSLog(@"%@",arr);}
//字典寫入檔案- (void)writeDic {    NSDictionary *dic = @{@"key":@"value"};    NSString *str = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];    NSString *toPath = [str stringByAppendingPathComponent:@"dictonry.txt"];    BOOL isSuccess = [dic writeToFile:toPath atomically:YES];    NSLog(@"%@",isSuccess ? @"成功" : @"失敗");    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:toPath];    NSLog(@"%@",dict);}
//NSData寫入檔案- (void)writeData {    NSString *tempPath = NSTemporaryDirectory();    NSString *toPath = [tempPath stringByAppendingPathComponent:@"data.txt"];    NSString *string = @"datadata";    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];    BOOL isSuccess = [data writeToFile:toPath atomically:YES];    NSLog(@"%@",isSuccess ? @"成功" : @"失敗");    NSData *getData = [NSData dataWithContentsOfFile:toPath];    NSString *str = [[NSString alloc] initWithData:getData encoding:NSUTF8StringEncoding];    NSLog(@"%@",str);}

2.preference

//Preference- (void)writeToPreference {    // NSUserDefaults 繼承自NSObject ,單例     通過kvc模式賦值    NSLog(@"%@",NSHomeDirectory());    //建立使用者索引對象    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    [defaults setInteger:100 forKey:@"money"];    //立即同步操作      對preference中的檔案進行修改後,立即同步    [defaults synchronize];    NSInteger money = [defaults integerForKey:@"money"];    NSLog(@"%ld",money);    [defaults setInteger:10000 forKey:@"MyMoney"];    [defaults synchronize];        NSInteger you = [defaults integerForKey:@"you"];    NSLog(@"%ld",(long)you);    if (money < 10) {        NSLog(@"there is no money");    } else {        NSLog(@"-100");        money -= 100;        [defaults setInteger:40 forKey:@"money"];        [defaults setInteger:1000 forKey:@"YourMoney"];    }    // NSUserDefaults 一般儲存一些比較小的資料,大部分用來存數值        //例子:判斷使用者是否第一次登陸    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];    BOOL isFirst = [userDefault boolForKey:@"isFirst"];    [userDefault setBool:YES forKey:@"isFirst"];    [userDefault synchronize];    if (!isFirst) {        NSLog(@"第一次登陸");    } else {        NSLog(@"不是第一次登陸");    }}

3.歸檔 / 反歸檔

複雜物件寫入檔案需要使用歸檔 ,讀取需要使用反歸檔,不能直接寫入檔案,數組中有複雜物件也要使用歸檔 / 反歸檔

複雜物件使用行歸檔和反歸檔,需要遵循NSCoding協議,並實現協議中- (void)encodeWithCoder:(NSCoder *)aCoder;   - (id)initWithCoder:(NSCoder *)aDecoder; 兩個方法

 

建立Person類

在Person.h中 遵循協議

////  Person.h//  07.24-DataPersistiser////  Created by lanouhn on 14/7/24.//  Copyright (c) 2014年 LCD. All rights reserved.//#import <Foundation/Foundation.h>@interface Person : NSObject <NSCoding>@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *gender;@property (nonatomic, assign) NSInteger age;@end

在Person.m中實現協議方法

////  Person.m//  07.24-DataPersistiser////  Created by lanouhn on 14/7/24.//  Copyright (c) 2014年 LCD. All rights reserved.//#import "Person.h"@implementation Person//當要歸檔時,對象會自動觸發這個方法- (void)encodeWithCoder:(NSCoder *)aCoder {    [aCoder encodeObject:self.name forKey:@"name"];    [aCoder encodeObject:self.gender forKey:@"gender"];    [aCoder encodeObject:@(self.age) forKey:@"age"];}- (id)initWithCoder:(NSCoder *)aDecoder {    self = [super init];    if (self) {        self.name = [aDecoder decodeObjectForKey:@"name"];        self.gender = [aDecoder decodeObjectForKey:@"gender"];        self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue];    }    return self;}@end

歸檔 / 反歸檔

- (void)archiver {        //把複雜檔案寫入檔案,先轉化為nsdata對象    //歸檔:歸檔的實質就是把其他類型的資料(person),先轉化為NSData,再寫入檔案。    Person *person = [[Person alloc] initWithName:@"rose" gender:@"girl" age:25];    //    NSKeyedArchiver  壓縮公用程式類,繼承自NSCoder,主要用於編碼    NSMutableData *data = [NSMutableData data] ;    NSKeyedArchiver *achiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];    //使用壓縮公用程式講Person壓到data中    [achiver encodeObject:person forKey:@"person"];    //完成壓縮,停掉壓縮公用程式    [achiver finishEncoding];        NSString *homePath = NSHomeDirectory();    NSString *toPath = [homePath stringByAppendingPathComponent:@"person.txt"];    BOOL isSuccess = [data writeToFile:toPath atomically:YES];    NSLog(@"%@",isSuccess ? @"成功" : @"失敗");        //複雜物件的讀取,反歸檔    //    NSKeyedUnarchiver    NSData *getData = [NSData dataWithContentsOfFile:toPath];    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:getData];    //解壓    Person *p1 = [unArchiver decodeObjectForKey:@"person"];    [unArchiver finishDecoding];}
 //集合NSArray NSDictionary 如果想進行歸檔和反歸檔,那麼它裡邊儲存的元素也要遵循NSCoding協議    Person *person1 = [[Person alloc] initWithName:@"jack" gender:@"男" age:20];    Person *person2 = [[Person alloc] initWithName:@"rose" gender:@"女" age:20];    NSArray *array = @[person1,person2];        NSMutableData *data = [NSMutableData data];        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];    [archiver encodeObject:array forKey:@"array"];    [archiver finishEncoding];        NSString *tmpPath = NSTemporaryDirectory();    NSString *toPath = [tmpPath stringByAppendingString:@"array.txt"];        BOOL isSuccess = [data writeToFile:toPath atomically:YES];    NSLog(@"%@",isSuccess ? @"成功" : @"失敗");    //反歸檔    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];    NSArray *unArchiverArray = [unArchiver decodeObjectForKey:@"array"];

 

 

相關文章

聯繫我們

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