標籤:
1.把要顯示的資料轉換為模型,把對象歸檔,然後把存起來的對象解析出來就可以使用
2.可以封裝起來方便使用,封裝的方法存入百度雲,需要的可以留言
/** 歸檔方法 */
-(void)archive
{
/**
* 常用的幾個檔案目錄 directory目錄
* NSDownloadsDirectory 下載檔案目錄
* NSDocumentDirectory 資料檔案目錄
* NSCachesDirectory 快取檔案目錄
* NSMoviesDirectory 電影檔案目錄
* NSPicturesDirectory 圖片檔案目錄
* NSMusicDirectory 音樂檔案目錄
*
*/
NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Document目錄下的第一個檔案對象
NSString *docPath = [myPaths firstObject];
//建立一個檔案並返回該檔案路徑
NSString *fileNamePath = [docPath stringByAppendingPathComponent:@"archive.data"];
//歸檔
[NSKeyedArchiver archiveRootObject:@"資料模型" toFile:fileNamePath];
//讀檔
NSString *duixaing = [NSKeyedUnarchiver unarchiveObjectWithFile:fileNamePath];
}
存檔的另一種方法,自己需要研究的是歸檔的路徑,歸檔的方法 ,讀檔的方法(註明用的是兩個不同的類,一個是存檔的類,一個是讀檔的類,)
存的資料是以二進位的形式存進手機本地的
/** 儲存資料進行歸檔 */
- (IBAction)saveBtn:(id)sender {
NSString *filePath = [self filePathWithfileName:@"student.archive"];
NSMutableData *theData = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];
studentsInfo *Info = [[studentsInfo alloc] init];
Info.sno = self.snoLabel.text;
Info.name = self.nameLabel.text;
Info.classes = self.classLabel.text;
[archiver encodeObject:Info forKey:@"mystudent"];
[archiver finishEncoding];
[theData writeToFile:filePath atomically:YES];
NSLog(@"%@",filePath);
}
/** 歸檔檔案讀取資料 */
- (IBAction)readBtn:(id)sender {
NSString *filePath = [self filePathWithfileName:@"student.archive"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
if (data.length > 0) {
NSKeyedUnarchiver *Unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
studentsInfo *Info = [Unarchiver decodeObjectForKey:@"mystudent"];
[Unarchiver finishDecoding];
self.snoLabel.text = Info.sno;
self.nameLabel.text = Info.name;
self.classLabel.text = Info.classes;
}
}
/** 返回一個在document檔案下的檔案的路徑(自己建立的檔案) */
-(NSString *)filePathWithfileName:(NSString *)fileName
{
NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myDocPath = [myPaths firstObject];
NSString *filename = [myDocPath stringByAppendingPathComponent:fileName];
return filename;
}
示封裝的虛擬碼,使用方法引用頭兒檔案既可。
iOS開發資料持久化,歸檔方法