數(shù)據(jù)持久化總結(jié)
1.屬性列表
2.對象歸檔
3.SQLite
4.Core Data
1.屬性列表
涉及到的主要類:NSUserDefaults,一般 [NSUserDefaults standardUserDefaults]就夠用了
@interface User : NSObject
@property (nonatomic, assign) NSInteger userID;
@property (nonatomic, copy) NSString *name;
@end
使用方法
1).分開存取
// 存
[[NSUserDefaults standardUserDefaults] setInteger:userID forKey:@”userID”];
[[NSUserDefaults standardUserDefaults] setObject:name forKey:@”name”];
// 取
NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey:@”userID”];
NSString* name = [[NSUserDefaults standardUserDefaults] stringForKey:@”name”];
2).按對象存取
// 存
[[NSUserDefaults standardUserDefaults] setObject:self forKey:@”user”];
// 取
User* u = [[NSUserDefaults standardUserDefaults]objectForKey”@”user”];
2.對象歸檔
要使用對象歸檔,對象必須實現(xiàn)NSCoding協(xié)議.大部分Object C對象都符合NSCoding協(xié)議,也可以在自定義對象中實現(xiàn)NSCoding協(xié)議,要實現(xiàn)NSCoding協(xié)議,實現(xiàn)兩個方法:
- (void) encodeWithCoder:(NSCoder *)encoder 與 -(void)initWithCoder:(NSCoder *)encoder
同時,建議對象也同時實現(xiàn)NSCopying協(xié)議,該協(xié)議允許復(fù)制對象,要實現(xiàn)NSCopying協(xié)議須實現(xiàn) -(id)copyWithZone:(NSZone *)zone 方法 。
@interface User : NSObject
@property (nonatomic, assign) NSInteger userID;
@property (nonatomic, copy) NSString *name;
@end
@implementation User
// 以下兩個方法一定要實現(xiàn),不然在調(diào)用的時候會crash
- (void)encodeWithCoder:(NSCoder *)aCoder;
{
// 這里放置需要持久化的屬性
[aCoder encodeObject:[NSNumber numberWithInteger:self.userID] forKey:@”userID”];
[aCoder encodeObject:self.nameforKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [self init])
{
//? 這里務(wù)必和encodeWithCoder方法里面的內(nèi)容一致,不然會讀不到數(shù)據(jù)
self.userID = [[aDecoder decodeObjectForKey:@"userID"] integerValue];
self.name= [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
// 使用方法
+ (BOOL)save {
NSError *error = nil;
// 確定存儲路徑,一般是Document目錄下的文件
NSString* fileName = [self getFileName];
NSString* filePath = [self getFilePath];
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(@”創(chuàng)建用戶文件目錄失敗”);
return NO;
}
return [NSKeyedArchiver archiveRootObject:self toFile:[fileName:userId]];
}
@end
3.SQLite3
SQLite是一個開源的嵌入式關(guān)系數(shù)據(jù)庫,它在2000年由D. Richard Hipp發(fā)布,它的減少應(yīng)用程序管理數(shù)據(jù)的開銷,SQLite可移植性好,很容易使用,很小,高效而且可靠。
SQLite嵌入到使用它的應(yīng)用程序中,它們共用相同的進程空間,而不是單獨的一個進程。從外部看,它并不像一個RDBMS,但在進程內(nèi)部,它卻是完整的,自包含的數(shù)據(jù)庫引擎。 嵌入式數(shù)據(jù)庫的一大好處就是在你的程序內(nèi)部不需要網(wǎng)絡(luò)配置,也不需要管理。因為客戶端和服務(wù)器在同一進程空間運行。SQLite 的數(shù)據(jù)庫權(quán)限只依賴于文件系統(tǒng),沒有用戶帳戶的概念。SQLite 有數(shù)據(jù)庫級鎖定,沒有網(wǎng)絡(luò)服務(wù)器。它需要的內(nèi)存,其它開銷很小,適合用于嵌入式設(shè)備。你需要做的僅僅是把它正確的編譯到你的程序。
關(guān)于SQLite的開發(fā)資料較多,這里不再細說。只是建議不直接操作SQLite庫,而是采用一些開源的第三方庫來進行操作。比如:
FMDB:https://github.com/ccgus/fmdb.git
對SQLite都做了不錯的封裝。
4.Core Data
Core Data本質(zhì)上是使用SQLite保存數(shù)據(jù),但是它不需要編寫任何SQL語句。
要使用Core Data,需要在Xcode中的數(shù)據(jù)模型編輯器中設(shè)計好各個實體以及定義好他們的屬性和關(guān)系。之后,通過操作這些對象,結(jié)合Core Data完成數(shù)據(jù)的持久化:
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
NSString *fieldName = [NSString stringWithFormat:@"test%d", i];
UITextField *theField = [self valueForKey:fieldName];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//創(chuàng) 建描述語句,需求Line對象。類似于在數(shù)據(jù)庫中限定為Line表。
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"? inManagedObjectContext:context];
[request setEntity:entityDescription];
//創(chuàng)建限制性語句,類似于SQL語句中的 where lineNum = i
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil){
NSLog(@”There was an error!”);
// Do whatever error handling is appropriate
}
if ([objects count] > 0){??? //如果符合條件的object存在,則取出
theLine = [objects objectAtIndex:0];
}
else {? //如果不存在,則插入一個新的.
theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:@”lineNum”];? //設(shè)置這個object的屬性,coredata會自動將其寫入sqlite
[theLine setValue:theField.text forKey:@"lineText"];
[request release];
}
}
下面是其取數(shù)據(jù)的過程:
Core_Data_PersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil)
{
NSLog(@”There was an error!”);
// Do whatever error handling is appropriate
}
//每一個對象在CoreData中都表示為一個NSManagedObject對象(類似于數(shù)據(jù)庫表中的每一行),他的屬性通過鍵/值 方式獲取
for (NSManagedObject *oneObject in objects)
{
NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];
NSString *lineText = [oneObject valueForKey:@"lineText"];
}
[request release];