簡易數(shù)據(jù)存儲
數(shù)據(jù)持久化分為本體持久化和云端持久化
本體持久化可以存在本地文件或數(shù)據(jù)庫碱屁。
云端可以存在iCloud蛾找,存在iCloud的數(shù)據(jù)可以是文件,也可以是Key-Value數(shù)據(jù)庫打毛。云端也可以將數(shù)據(jù)存在第三方的網(wǎng)絡(luò)服務(wù)器上。
NSData
NSData是一個表示通用數(shù)據(jù)的類幻枉。可以進(jìn)行讀展辞、寫和訪問內(nèi)存里的內(nèi)容。
圖片
創(chuàng)建UIImage對象
文件在bundle中
NSData
CGContext
CGImageRef CGBitmapContextCreateImage(ctx);
保存 UIImage對象
via data
NSData *UIImagePNGRepresentaion(UIImage *image);
NSData *UIImageJPEGRepresentaion(UIImage *image, CGFloat compressionQuality);
NSString與存儲
NSString的存儲主要處理的是文本讀寫和文件路徑
Key Value數(shù)據(jù)
讀
+(NSDictionary<KeyType, ObjectType>*)dictionaryWithContentsOfFile:(NSString*)
+(NSDictionary<KeyType, ObjectType>*)dictionaryWithContentsOfURL:(NSURL*)
寫
-(BOOL)writeToFile:(NSString*)atomically:(BOOL)
-(BOOL)writeToURL:(NSURL*)atomically:(BOOL)
配置參數(shù)
配置參數(shù)用來保存默認(rèn)值洽腺,如果是用戶需要經(jīng)常修改的參數(shù)建議使用自己的UI覆旱,不常改的放在settings bundle。
Domain:
NSArgumentDomain:Xcode.app/Contents/MacOS/Xcode-IndexOnOpen NO
Application:NSUserDefaults
NSGlobalDomain:defaults read NSGlobalDomain
Languages:AppleLanguage 指定用戶使用的語言
NSRegistrationDomain:[NSUserDefaults registerDefaults:]提供的默認(rèn)值
Mac OS X 的 defaults 命令
defaults read<domain>[key]
defaults find Xcode.IDE
NSUserDefault
訪問
[NSUserDefaults standardUserDefaults] //拿回一個本地的default
[NSUbiquitousKeyValueStore defaultStore] //iCloud
登記默認(rèn)值
[NSUserDefaults registerDefaults:dict]
訪問
讀-<type>ValueForKey:
寫-set<Type>:forKey:
Settings Bundle
Settings.bundle in app root
Access via standardDefaults
沙盒扣唱、文件與對象歸檔
沙盒是在受限的安全環(huán)境中運(yùn)行應(yīng)用程序的一種做法团南,這種做法是要限制授予應(yīng)用程序的代碼訪問權(quán)限炼彪。
NSHomeDirectory():
/Documents:程序的文件數(shù)據(jù)保存在該目錄下,iTunes備份時包括該目錄
/Library:存儲程序的默認(rèn)設(shè)置或其它狀態(tài)信息
/Library/Caches: 緩存文件辐马,iTunes不備份,不會再應(yīng)用退出刪除
/tmp:創(chuàng)建臨時文件的地方冗疮,重啟時會弄丟
NSString *NSTemporaryDirectory (void);
NSArray<NSString > NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask, BOOL expandTilde);
模擬器沙盒的環(huán)境目錄
~/Library/Developer/CoreSimulator/Devices/
在MAC下運(yùn)行一下命名就可以看見
defaults write com.apple.finder AppleShowAllFiles -bool true
App Bundle
通用的文件管理需要使用NSFileManager檩帐。
獲取方法术幔,使用sharedManager //線程不安全
alloc-init //線程安全湃密,可以多線程操作
目錄
文件
安全性選項(xiàng):
NSFileProtectionComplete 完全保護(hù)
NSFileProtectionCompleteUnlessOpen 如果自己的程序打開過就可以訪問,適合有后臺任務(wù)的程序
NSFileProtectionCompleteUntilFirstUserAuthentication 只要用戶解鎖過這個設(shè)備揍障,就可以訪問
iTunes File Sharing
在Info.plist設(shè)置中將UIFileSharingEnabled設(shè)置為YES,就可以讓iTunes訪問到這個程序存貯的數(shù)據(jù)
應(yīng)用間共享文件
用戶授權(quán)+操作系統(tǒng)代為操作
本機(jī)“Open in"
-UIDocumentInteractionController
文檔地址:https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
iCloud
-UIDocumentPickerViewController
iCloud文件上傳和下載需要時間毒嫡,操作同一文件可能引發(fā)沖突幻梯。但是iCloud在多部機(jī)器之間訪問同一個文件將會非常方便。
使用步驟:
Add the "iCloud"entitlement to your App ID
Add the "iCloud sontainers" entitlement to your App ID
Add the "iCloud" entitlement to your entitlement file
Link CloudKit.framework
通過iCloud讀取文件有兩種模式碘梢,一種是副本模式,把文件從網(wǎng)絡(luò)導(dǎo)入到本地使用煞躬。還有一種是直接訪問,提供一個URL通過URL來訪問文件在扰。
對象歸檔
對象歸檔的過程
存貯
1雷客、對象本身要準(zhǔn)守NSCoding協(xié)議。
2搅裙、按照協(xié)議寫一個編碼函數(shù)裹芝,將需要的字段寫進(jìn)去娜汁。
3嫂易、調(diào)用NSKeyedArchiver archiveRootObject
取出
1存炮、調(diào)用NSKeyedUnarchiver unarchiveObjectWithFile
2蜈漓、掉用initWithCoder方法讀取文件
SQLite3
SQL是關(guān)系數(shù)據(jù)庫,由表和字段組成融虽。可以使用關(guān)系運(yùn)算有额。
SQL語言
DML:SELECT/INSERT/UPGRADE/DELETE/MERGE
DDL:CREATE/ALTER/DROP
DCL:GRANT/REVOKE
TCL:ROLLBACK/SET TRANSACTION
SQLite是一個開源的嵌入式關(guān)系數(shù)據(jù)庫
項(xiàng)目主頁:http://www.sqlite.org
嵌入式意味著引入程序庫,而非與服務(wù)器通信
完整的SQLite SQL參考:http://www.sqlite.org/lang.html
查詢數(shù)據(jù)庫
SQLite 刪除修改數(shù)據(jù)
在iOS中使用SQLite
鏈接libSQLite3.dylib
使用SQLite3函數(shù)
打開/新建數(shù)據(jù)庫文件
執(zhí)行SQL命令
關(guān)閉數(shù)據(jù)庫
SQLite3的API是一個純C語言的API
FMDB
介紹網(wǎng)址:https://github.com/ccgus/fmdb
基本用法:
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
[db open]
FMResultSet *rs = [db executeQuery:@"SELECT * FROM myTable"];
while([re next]){...}
[rs<type>ForColumnIndex:idx];
[db close];
更新語句
[db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary){}]
[db executeUpdate:@"INSERT INTO authors(identifier, name, date, comment)VALUES(?,?,?,?)",@(identifier), name, date, comment?:[NSNull null]];
CoreData
CoreData是蘋果公司提供的對象持久化框架,他不是數(shù)據(jù)庫萤衰,通常使用數(shù)據(jù)庫作為底層存儲,也可以使用XML文件脆栋。
CoreData是由Managed Object Context, Persistent Store Coordinator, Persistent Object Store, Store File這四部分組成
CoreData的使用
在項(xiàng)目開始時要勾選Use Core Data
進(jìn)入項(xiàng)目后需要定義一個數(shù)據(jù)模型
之后AppDelegate.m文件中會自動幫我們生成一個context來存貯數(shù)據(jù)椿争。
存入對象的方法:
NSManagedObject *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context]; //創(chuàng)建一個Student對象
[student setValue:@"Mike"forKey:@"name"];
[student setValue:[NSNumber numberWithInt:29]forKey:@"age"]; //填充屬性
NSManagedObject *work = [NSEntityDescription insertNewObjectForEntityForName:@"homeWork"inManagedObjectContext:context]; //創(chuàng)建一個Homework對象
[work setValue:@"123456"forKey:@"no"]; //建立關(guān)聯(lián)關(guān)系
[student setValue:work forKey:@"homeWork"];
NSError *error = nil;
BOOL success = [context save:&error]; //保存數(shù)據(jù)
查詢數(shù)據(jù)內(nèi)容
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"]; //查找一個名字叫Student的數(shù)據(jù)
//排序、過濾(名字用J開頭的數(shù)據(jù))
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]];
request.predicate = [NSPredicate predicateWithFormat:@"name like %@",@"J"];
//執(zhí)行
NSError *error = nil;
NSArray *objs = [context executeFetchRequest:request error:&error];
if(error){[NSException raise:@"Query failed" format:@"%@", [error localizedDescription]];}
//遍歷結(jié)果
for (NSManagedObject *obj in objs){
NSlog(@"name=%@", [obj valueForKey:@"name"]
}
刪除數(shù)據(jù)
[context deleteObject:managedObject];
NSError *error = nil;
[context save:&error];
if(error){
[NSException raise:@"Failed to delete!"format:@"%@",[error localizedDescription]];
}
用NSFetchedResultsController簡化結(jié)果顯示