標籤: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屬性
- #include <sys/xattr.h>
- - (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
- {
- const char* filePath = [[URL path] fileSystemRepresentation];
- const char* attrName = "com.apple.MobileBackup";
- u_int8_t attrValue = 1;
- int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
- return result == 0;
- }
(3)得到目錄位址
URLsForDirectory:inDomains: method 返回NSURL形式的目錄位址
NSSearchPathForDirectoriesInDomains 返回字串形式的目錄位址
NSHomeDirectory 返回程式根目錄
NSTemporaryDirectory 返回臨時檔案目錄
(4)相關變數定義
- NSSearchPathDirectory
- enum {
- NSApplicationDirectory = 1,//Supported applications (/Applications)
- NSDemoApplicationDirectory,//Unsupported applications and demonstration versions
- NSDeveloperApplicationDirectory,//Developer applications (/Developer/Applications)
- NSAdminApplicationDirectory,//System and network administration applications
- NSLibraryDirectory,//Various user-visible documentation, support, and configuration files (/Library)
- NSDeveloperDirectory,//Developer resources (/Developer)
- NSUserDirectory,//User home directories (/Users)
- NSDocumentationDirectory,//
- NSDocumentDirectory,//
- NSCoreServiceDirectory,//Location of core services (System/Library/CoreServices)
- NSAutosavedInformationDirectory = 11,//Location of user’s autosaved documents Library/Autosave Information
- NSDesktopDirectory = 12,//
- NSCachesDirectory = 13,//Location of discardable cache files (Library/Caches)
- NSApplicationSupportDirectory = 14,//Location of application support files (Library/Application Support)
- NSDownloadsDirectory = 15,//
- NSInputMethodsDirectory = 16,//
- NSMoviesDirectory = 17,//
- NSMusicDirectory = 18,//
- NSPicturesDirectory = 19,//
- NSPrinterDescriptionDirectory = 20,//
- NSSharedPublicDirectory = 21,//
- NSPreferencePanesDirectory = 22,//
- NSItemReplacementDirectory = 99,//
- NSAllApplicationsDirectory = 100,//
- NSAllLibrariesDirectory = 101//
- };
- typedef NSUInteger NSSearchPathDirectory;
- enum {
- NSUserDomainMask = 1,//使用者主目錄中
- NSLocalDomainMask = 2,//當前機器中
- NSNetworkDomainMask = 4,//網路中可見的主機
- NSSystemDomainMask = 8,//系統目錄,不可修改(/System)
- NSAllDomainsMask = 0x0ffff,//全部
- };
- 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:
- – archiver:didEncodeObject:
- – archiverDidFinish:
- – archiver:willEncodeObject:
- – archiverWillFinish:
- – 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:
- – unarchiver:cannotDecodeObjectOfClassName:originalClasses:
- – unarchiver:didDecodeObject:
- – unarchiver:willReplaceObject:withObject:
- Finishing Decoding
- – unarchiverDidFinish:
- – 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,記得儲存。結束過程樣本:
- NSManagedObjectContext *managedObjectContext = nil;
- // 得到模版
- NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"YOUR_XCDATAMODELD_FILE_NAME" withExtension:@"momd"];
- NSManagedObjectModel* managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
- // 具體檔案,DOCUMENT_DICRECTORY應該是nsurl的..
- NSURL *storeURL = [@"DOCUMENT_DICRECTORY" URLByAppendingPathComponent:@"SQLITE.sqlite"];
- NSError *error = nil;
- NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
- // 使用SQLite儲存
- if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
- // 出錯
- }
- else
- {
- // 得到操作空間
- managedObjectContext = [[NSManagedObjectContext alloc] init];
- [managedObjectContext setPersistentStoreCoordinator:coordinator];
- }
- // 得到具體的表
- NSEntityDescription *entityDescription = [NSEntityDescription
- entityForName:@"ONE_ENTITY_NAME"
- inManagedObjectContext:managedObjectContext];
- // 動作陳述式
- NSFetchRequest *request = [[NSFetchRequest alloc] init];
- [request setEntity:entityDescription];
- // 動作陳述式的條件
- NSPredicate *pred = [NSPredicate predicateWithFormat:@"PREDICATE_SECTION"];
- [request setPredicate:pred];
- NSManagedObject *manageObject = nil;
- // 執行操作,得到多條具體資料
- NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
- if (objects == nil) {
- // 出錯
- }
- if ([objects count] > 0)
- // 多條,取第一條
- manageObject = [objects objectAtIndex:0];
- else
- // 沒有相應的,就建立
- manageObject = [NSEntityDescription
- insertNewObjectForEntityForName:@"TABLE_NAME"
- inManagedObjectContext:managedObjectContext];
- // 改變她的一個欄位的值
- [manageObject setValue:@"VALUE" forKey:@"ONE_FIELD_NAME_OF_THE_TABLE"];
- [request release];
- // 儲存,結束
- [managedObjectContext save:&error];
複製代碼
(四).SQLite
引入SQLite庫,加入標頭檔,使用C API操作.繁瑣的地方在於只能儲存c資料格式,需要來迴轉換.過程樣本:
- // 聲明資料庫
- sqlite3 *database;
- // 開啟
- if (sqlite3_open("資料庫檔案路徑", &database) != SQLITE_OK) {
- sqlite3_close(database);
- // 出錯
- }
- char *errorMsg;
- // 執行無返回語句
- if (sqlite3_exec (database, "增刪改創語句",NULL, NULL, &errorMsg) != SQLITE_OK) {
- sqlite3_close(database);
- // 出錯
- }
- sqlite3_stmt *statement;
- // 執行查詢語句
- if (sqlite3_prepare_v2(database, "查詢語句",-1, &statement, nil) == SQLITE_OK) {
- // 遍曆結果
- while (sqlite3_step(statement) == SQLITE_ROW) {
- int row = sqlite3_column_int(statement, 0);
- // 第一列資料
- char *rowData = (char *)sqlite3_column_text(statement, 1);
- }
- // 結束遍曆
- sqlite3_finalize(statement);
- }
- // 關閉資料庫
- sqlite3_close(database);
ios開發 資料存放區