詳解iPhone應(yīng)用開發(fā)之?dāng)?shù)據(jù)持久化
iPhone應(yīng)用開發(fā)之數(shù)據(jù)持久化是本文要介紹的內(nèi)容,主要是來學(xué)習(xí)iphone應(yīng)用中數(shù)據(jù)庫的使用,具體內(nèi)容來看詳細(xì)內(nèi)容。
1、plist
局限性:只有它支持的數(shù)據(jù)類型可以被序列化,存儲到plist中。無法將其他Cocoa對象存儲到plist,更不能將自定義對象存儲。
支持的數(shù)據(jù)類型:Array,Dictionary,Boolean,Data,Date,Number和String.如圖:
xml文件 數(shù)據(jù)類型截圖~其中基本數(shù)據(jù)(Boolean,Data,Date,Number和String.)、容器 (Array,Dictionary)
寫入xml過程:先將基本數(shù)據(jù)寫入容器 再調(diào)用容器的 writeToFile 方法,寫入。
- [theArray writeToFile:filePath atomically:YES];
擁有此方法的數(shù)據(jù)類型有,如圖所示:
atomically參數(shù),將值設(shè)置為 YES。寫入文件的時候,將不會直接寫入指定路徑,而是將數(shù)據(jù)寫入到一個“輔助文件”,寫入成功后,再將其復(fù)制到指定路徑。
2、Archiver
特點:支持復(fù)雜的數(shù)據(jù)對象。包括自定義對象。對自定義對象進(jìn)行歸檔處理,對象中的屬性需滿足:為基本數(shù)據(jù)類型(int or float or......),或者為實現(xiàn)了NSCoding協(xié)議的類的實例。自定義對象的類也需要實現(xiàn)NSCoding。
NSCoding 方法:
- -(id)initWithCoder:(NSCoder *)decoder; - (void)encodeWithCoder:(NSCoder *)encoder;
參數(shù)分別理解為解碼者和編碼者。
例如創(chuàng)建自定義類Student:NSObject <NSCoding>
- #import "Student.h"
- @implementation Student
- @synthesize studentID;
- @synthesize studentName;
- @synthesize age;
- @synthesize count;
- - (void)encodeWithCoder:(NSCoder *)encoder
- {
- [encoder encodeObject: studentID forKey: kStudentId];
- [encoder encodeObject: studentName forKey: kStudentName];
- [encoder encodeObject: age forKey: kAge];
- [encoder encodeInt:count forKey:kCount];
- }18 19 - (id)initWithCoder:(NSCoder *)decoder
- {
- if (self == [super init]) {
- self.studentID = [decoder decodeObjectForKey:kStudentId];
- self.studentName = [decoder decodeObjectForKey:kStudentName];
- self.age = [decoder decodeObjectForKey:kAge];
- self.count = [decoder decodeIntForKey:kCount];
- }
- return self;
- }
- @end
編碼過程:
- /*encoding*/
- Student *theStudent = [[Student alloc] init];
- theStudent.studentID = @"神馬";
- theStudent.studentName = @"shenma";
- theStudent.age = @"12";
- NSMutableData *data = [[NSMutableData alloc] init];
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
- [archiver encodeObject: theStudent forKey:@"student"];
NSKeyedArchiver可以看作“加密器”,將student實例編碼后存儲到data
NSMutableData 可看作“容器”,并由它來完成寫入文件操作(inherits NSData)。
解碼過程:
- /*unencoding*/
- Student *studento = [[Student alloc] init];
- data = [[NSData alloc] initWithContentsOfFile:documentsPath];
- NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
- studento = [unarchiver decodeObjectForKey:@"student"];
- [unarchiver finishDecoding];
根據(jù)鍵值key得到反序列化后的實例。
3、SQLite
數(shù)據(jù)庫操作~
小結(jié):詳解iPhone應(yīng)用開發(fā)之數(shù)據(jù)持久化的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對你有所幫助!