詳解iPhone應(yīng)用開(kāi)發(fā)之?dāng)?shù)據(jù)持久化
iPhone應(yīng)用開(kāi)發(fā)之數(shù)據(jù)持久化是本文要介紹的內(nèi)容,主要是來(lái)學(xué)習(xí)iphone應(yīng)用中數(shù)據(jù)庫(kù)的使用,具體內(nèi)容來(lái)看詳細(xì)內(nèi)容。
1、plist
局限性:只有它支持的數(shù)據(jù)類型可以被序列化,存儲(chǔ)到plist中。無(wú)法將其他Cocoa對(duì)象存儲(chǔ)到plist,更不能將自定義對(duì)象存儲(chǔ)。
支持的數(shù)據(jù)類型:Array,Dictionary,Boolean,Data,Date,Number和String.如圖:
xml文件 數(shù)據(jù)類型截圖~其中基本數(shù)據(jù)(Boolean,Data,Date,Number和String.)、容器 (Array,Dictionary)
寫(xiě)入xml過(guò)程:先將基本數(shù)據(jù)寫(xiě)入容器 再調(diào)用容器的 writeToFile 方法,寫(xiě)入。
- [theArray writeToFile:filePath atomically:YES];
擁有此方法的數(shù)據(jù)類型有,如圖所示:
atomically參數(shù),將值設(shè)置為 YES。寫(xiě)入文件的時(shí)候,將不會(huì)直接寫(xiě)入指定路徑,而是將數(shù)據(jù)寫(xiě)入到一個(gè)“輔助文件”,寫(xiě)入成功后,再將其復(fù)制到指定路徑。
2、Archiver
特點(diǎn):支持復(fù)雜的數(shù)據(jù)對(duì)象。包括自定義對(duì)象。對(duì)自定義對(duì)象進(jìn)行歸檔處理,對(duì)象中的屬性需滿足:為基本數(shù)據(jù)類型(int or float or......),或者為實(shí)現(xiàn)了NSCoding協(xié)議的類的實(shí)例。自定義對(duì)象的類也需要實(shí)現(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
編碼過(guò)程:
- /*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實(shí)例編碼后存儲(chǔ)到data
NSMutableData 可看作“容器”,并由它來(lái)完成寫(xiě)入文件操作(inherits NSData)。
解碼過(guò)程:
- /*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得到反序列化后的實(shí)例。
3、SQLite
數(shù)據(jù)庫(kù)操作~
小結(jié):詳解iPhone應(yīng)用開(kāi)發(fā)之數(shù)據(jù)持久化的內(nèi)容介紹完了,希望通過(guò)本文的學(xué)習(xí)能對(duì)你有所幫助!