iOS 資料的儲存和讀取之歸檔
阿新 • • 發佈:2019-02-12
歸檔四一種很常見的檔案儲存方法,幾乎任何型別的物件都能夠被歸檔儲存(實際上是一種檔案儲存形式)。
使用NSKeyedArichiver進行歸檔,用NSKeyedUnarichiver進行解歸檔。這種方式會在寫入、讀出資料之前堆資料進行序列化、反序列化操作。
一,簡單歸檔 archiveRootObject
(1),歸檔
- NSString *homeDictionary = NSHomeDirectory();//獲取根目錄
-
NSString *homePath = [homeDictionary stringByAppendingPathComponent:@"test.archiver"
- BOOL flag = [NSKeyedArchiver archiveRootObject:@”歸檔測試” toFile:homePath];//歸檔一個字串
(2),解歸檔
[NSKeyedUnarchiver unarchiveObjectWithFile:homePath]
;
缺點:只能把一個物件歸檔進一個檔案中。
二,歸檔多個物件
舉例:歸檔CGPoint點、字串和整數,使用encode方法進行,最後再寫入檔案;
(1),歸檔
- //歸檔資料
- CGPoint point = CGPointMake(320.0, 480.0);
-
NSString *info = @"歸檔測試"
- NSInteger value = 1000;
- NSString *multiHomePath = [NSHomeDirectory() stringByAppendingPathComponent:@"multiTest.archiver"];
- NSMutableData *data = [[NSMutableData alloc]init];
- NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
- //對多個物件進行歸檔
-
[archvier encodeCGPoint:point forKey:@"kPoint"
- [archvier encodeObject:info forKey:@"kInfo"];
- [archvier encodeInteger:value forKey:@"kValue"];
- [archvier finishEncoding];
- [data writeToFile:multiHomePath atomically:YES];
(2),解歸檔
- NSMutableData *dataR = [[NSMutableData alloc]initWithContentsOfFile:multiHomePath];
- NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:dateR];
- CGPoint pointR = [unarchiver decodeCGPointForKey:@"kPoint"];
- NSString *infoR = [unarchiver decodeObjectForKey:@"kInfo"];
- NSInteger valueR = [unarchiver decodeIntegerForKey:@"kValue"];
- [unarchiver finishDecoding];
- NSLog(@"%f,%f,%@,%d",pointR.x,pointR.y,infoR,valueR);
限制:歸檔的都是一些基本資料型別。