ios開發 資料存放區

來源:互聯網
上載者:User

標籤:des   io   ar   os   使用   sp   for   strong   檔案   

喜好設定設定儲存

NSUserDefaults 以及通過它控制的SettingBundle  NSUserDefaults 用來儲存一些設定,他會自動寫到何時的位置。
NSUbiquitousKeyValueStore 多平台同步設定,限制是大小64k,開啟entitlement,唯一Apple ID(還要考慮無法串連到iCloud網路時的情形)

 

一.檔案儲存體


(1)目錄描述

<Application_Home>/AppName.app bundle目錄,包括程式本身。往裡面些東西會導致簽名改變和重啟程式。首次同步處理後iTunes不備份此目錄。
<Application_Home>/Documents/ 儲存使用者文檔和程式資料。通過檔案分享權限設定可以使其可見。iTunes備份之。
<Application_Home>/Documents/Inbox 其他程式要求本程式開啟的文檔。可讀刪,不可增加修改。要改變可以先移出來。iTunes備份之。
<Application_Home>/Library/ 非使用者資料檔案儲存的根目錄。用其中標準或自訂的檔案夾備份不被使用者可見的資料。不應用這個目錄存放使用者資料。iTunes備份之。
  ~Library/Application Support/<bundle_ID> 為使用者建立管理的資源和資料檔案。用這個目錄存放程式狀態資訊,下載的檔案甚至使用者建立但同意你管理的資料。自動儲存檔案。
  ~/Library/Caches/<bundle_ID> 用來儲存快取檔案或者程式可以簡單重建的檔案的目錄。
<Application_Home>/tmp/ 臨時檔案目錄,可能被系統刪除,不應期望始終存在。不被iTunes備份。
另:

(2)離線資料
可以下載,或重新建立,但使用者希望在離線時也能訪問這些資料。存放在<Application_Home>/Documents 或<Application_Home>/Library/Private Documents ,並標記為"do not backup"。這兩個位置的資料在低儲存空間時都會保留,而"do not backup"屬性會阻止iTunes或iCloud備份。應用不再需要離線資料檔案時,應該儘快刪除,以避免浪費使用者的儲存空間。設定do not back up屬性

  1. #include <sys/xattr.h>
  2. - (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
  3. {
  4.     const char* filePath = [[URL path] fileSystemRepresentation];
  5.     const char* attrName = "com.apple.MobileBackup";
  6.     u_int8_t attrValue = 1;
  7.     int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
  8.     return result == 0;
  9. }

(3)得到目錄位址


URLsForDirectory:inDomains: method 返回NSURL形式的目錄位址
NSSearchPathForDirectoriesInDomains 返回字串形式的目錄位址
NSHomeDirectory 返回程式根目錄
NSTemporaryDirectory 返回臨時檔案目錄

(4)相關變數定義

  1. NSSearchPathDirectory
  2. enum {
  3. NSApplicationDirectory = 1,//Supported applications (/Applications)
  4. NSDemoApplicationDirectory,//Unsupported applications and demonstration versions
  5. NSDeveloperApplicationDirectory,//Developer applications (/Developer/Applications)
  6. NSAdminApplicationDirectory,//System and network administration applications
  7. NSLibraryDirectory,//Various user-visible documentation, support, and configuration files (/Library)
  8. NSDeveloperDirectory,//Developer resources (/Developer)
  9. NSUserDirectory,//User home directories (/Users)
  10. NSDocumentationDirectory,//
  11. NSDocumentDirectory,//
  12. NSCoreServiceDirectory,//Location of core services (System/Library/CoreServices)
  13. NSAutosavedInformationDirectory = 11,//Location of user’s autosaved documents Library/Autosave Information
  14. NSDesktopDirectory = 12,//
  15. NSCachesDirectory = 13,//Location of discardable cache files (Library/Caches)
  16. NSApplicationSupportDirectory = 14,//Location of application support files (Library/Application Support)
  17. NSDownloadsDirectory = 15,//
  18. NSInputMethodsDirectory = 16,//
  19. NSMoviesDirectory = 17,//
  20. NSMusicDirectory = 18,//
  21. NSPicturesDirectory = 19,//
  22. NSPrinterDescriptionDirectory = 20,//
  23. NSSharedPublicDirectory = 21,//
  24. NSPreferencePanesDirectory = 22,//
  25. NSItemReplacementDirectory = 99,//
  26. NSAllApplicationsDirectory = 100,//
  27. NSAllLibrariesDirectory = 101//
  28. };
  29. typedef NSUInteger NSSearchPathDirectory;

  1. enum {
  2. NSUserDomainMask = 1,//使用者主目錄中
  3. NSLocalDomainMask = 2,//當前機器中
  4. NSNetworkDomainMask = 4,//網路中可見的主機
  5. NSSystemDomainMask = 8,//系統目錄,不可修改(/System)
  6. NSAllDomainsMask = 0x0ffff,//全部
  7. };
  8. typedef NSUInteger NSSearchPathDomainMask;
  

二.儲存方式

(1).屬性列表(plist)
array,dictionary,data,string,NSNumber,NSDate 等ns對象直接寫入plist檔案中儲存.
(2).歸檔檔案
實現NSCoding協議(NSCopy也要實現?沒實現也成功了。。)編解碼類說明NSKeyedArchiver建立
- (id)initForWritingWithMutableData:(NSMutableData *)data // 歸檔資料寫到data中
歸檔資料
+ (NSData *)archivedDataWithRootObject:(id)rootObject // 歸檔到data中
+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path // 歸檔到檔案中
- (void)finishEncoding // 調用後不能繼續歸檔資料,歸檔結束必須調用(公用方法歸檔的不用理這個了)
– outputFormat // data編碼方式,xml還是二進位
– setOutputFormat:
編碼資料
– encodeBool:forKey:
– encodeBytes:length:forKey:
– encodeConditionalObject:forKey:
– encodeDouble:forKey:
– encodeFloat:forKey:
– encodeInt:forKey:
– encodeInt32:forKey:
– encodeInt64:forKey:
– encodeObject:forKey:
代理委託
– delegate
– setDelegate:

  1. – archiver:didEncodeObject:
  2. – archiverDidFinish:
  3. – archiver:willEncodeObject:
  4. – archiverWillFinish:
  5. – archiver:willReplaceObject:withObject:
複製代碼類和類名
+ setClassName:forClass:
+ classNameForClass:
– setClassName:forClass:
– classNameForClass:
異常
extern NSString *NSInvalidArchiveOperationException;NSKeyedUnarchiver建立
– initForReadingWithData:
取消歸檔
+ (id)unarchiveObjectWithData:(NSData *)data // 從data中得到實現歸檔的對象
+ (id)unarchiveObjectWithFile:(NSString *)path // 從檔案中得到
解碼資料
- (BOOL)containsValueForKey:(NSString *)key // 是否包含給定的key編碼對象
– decodeBoolForKey:
– decodeBytesForKey:returnedLength:
– decodeDoubleForKey:
– decodeFloatForKey:
– decodeIntForKey:
– decodeInt32ForKey:
– decodeInt64ForKey:
– decodeObjectForKey:
- (void)finishDecoding // 通知委託解碼結束,調用後不能再繼續解碼
代理委託
– delegate
– setDelegate:
  1. – unarchiver:cannotDecodeObjectOfClassName:originalClasses:
  2. – unarchiver:didDecodeObject:
  3. – unarchiver:willReplaceObject:withObject:
  4. Finishing Decoding
  5. – unarchiverDidFinish:
  6. – unarchiverWillFinish:
複製代碼類名
+ setClass:forClassName:
+ classForClassName:
– setClass:forClassName:
– classForClassName:
異常
NSString *NSInvalidUnarchiveOperationException;  (3).CoreData
xcdatamodeld檔案中Entity的三種屬性:
Attributes: 對應的Obj-c類的介面變數.
Relationships: Entity之間的關係,to-one,or to-many.
Fetched properties: 對上面Relationship的過濾?參考參考1對應檔案儲存體形式COREDATA_EXTERN NSString * const NSSQLiteStoreType NS_AVAILABLE(10_4, 3_0);// SQLite形式儲存
COREDATA_EXTERN NSString * const NSXMLStoreType NS_AVAILABLE(10_4, NA);// ios不可用
COREDATA_EXTERN NSString * const NSBinaryStoreType NS_AVAILABLE(10_4, 3_0);// 二進位形式儲存
COREDATA_EXTERN NSString * const NSInMemoryStoreType NS_AVAILABLE(10_4, 3_0);// 記憶體中基本使用過程(括弧中參考sql術語)
NSManagedObjectModel對象 擷取工程中xcdatamodeld檔案設定的模版(就是你的資料庫有哪些表,表中有哪些欄位的一種說明)
NSPersistentStoreCoordinator對象 根據上面的模版產生或對應的一個檔案(資料庫檔案,具體的資料檔案)
NSManagedObjectContext對象 上面檔案的操作的空間,增刪改查都通過這裡進行
NSEntityDescription對象 得到上面context中的一個表
NSFetchRequest對象 對上面表的一些具體操作,增刪改查
- (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error; 使用這個方法執行上面的request
如果增刪改了context,記得儲存。結束過程樣本:
  1. NSManagedObjectContext *managedObjectContext = nil;
  2. // 得到模版
  3. NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"YOUR_XCDATAMODELD_FILE_NAME" withExtension:@"momd"];
  4. NSManagedObjectModel* managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  5. // 具體檔案,DOCUMENT_DICRECTORY應該是nsurl的..
  6. NSURL *storeURL = [@"DOCUMENT_DICRECTORY" URLByAppendingPathComponent:@"SQLITE.sqlite"];
  7. NSError *error = nil;
  8. NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
  9. // 使用SQLite儲存
  10. if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
  11. // 出錯
  12. else
  13. {
  14. // 得到操作空間
  15. managedObjectContext = [[NSManagedObjectContext alloc] init];
  16. [managedObjectContext setPersistentStoreCoordinator:coordinator];
  17. }
  18. // 得到具體的表
  19. NSEntityDescription *entityDescription = [NSEntityDescription
  20. entityForName:@"ONE_ENTITY_NAME"
  21. inManagedObjectContext:managedObjectContext];
  22. // 動作陳述式
  23. NSFetchRequest *request = [[NSFetchRequest alloc] init];
  24. [request setEntity:entityDescription];
  25. // 動作陳述式的條件
  26. NSPredicate *pred = [NSPredicate predicateWithFormat:@"PREDICATE_SECTION"];
  27. [request setPredicate:pred];
  28. NSManagedObject *manageObject = nil;
  29. // 執行操作,得到多條具體資料
  30. NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
  31. if (objects == nil) {
  32. // 出錯
  33. }
  34. if ([objects count] > 0)
  35. // 多條,取第一條
  36. manageObject = [objects objectAtIndex:0];
  37. else
  38. // 沒有相應的,就建立
  39. manageObject = [NSEntityDescription
  40. insertNewObjectForEntityForName:@"TABLE_NAME"
  41. inManagedObjectContext:managedObjectContext];
  42. // 改變她的一個欄位的值 
  43. [manageObject setValue:@"VALUE" forKey:@"ONE_FIELD_NAME_OF_THE_TABLE"];
  44. [request release];
  45. // 儲存,結束
  46. [managedObjectContext save:&error];
複製代碼 (四).SQLite
引入SQLite庫,加入標頭檔,使用C API操作.繁瑣的地方在於只能儲存c資料格式,需要來迴轉換.過程樣本:
  1. // 聲明資料庫
  2. sqlite3 *database;
  3. // 開啟
  4. if (sqlite3_open("資料庫檔案路徑", &database) != SQLITE_OK) {
  5. sqlite3_close(database);
  6. // 出錯
  7. }
  8. char *errorMsg;
  9. // 執行無返回語句
  10. if (sqlite3_exec (database, "增刪改創語句",NULL, NULL, &errorMsg) != SQLITE_OK) {
  11. sqlite3_close(database);
  12. // 出錯
  13. }
  14. sqlite3_stmt *statement;
  15. // 執行查詢語句
  16. if (sqlite3_prepare_v2(database, "查詢語句",-1, &statement, nil) == SQLITE_OK) {
  17. // 遍曆結果
  18. while (sqlite3_step(statement) == SQLITE_ROW) {
  19. int row = sqlite3_column_int(statement, 0);
  20. // 第一列資料
  21. char *rowData = (char *)sqlite3_column_text(statement, 1);
  22. }
  23. // 結束遍曆
  24. sqlite3_finalize(statement);
  25. }
  26. // 關閉資料庫
  27. sqlite3_close(database);

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.