夫天下未有徒侍人而可自存者。 —— 《李鴻章傳》 梁啟超
-
NSData 與 NSMutableArray
NSData撰糠,NSMutableArray (or NSArray)者酥馍,類也。
兩者皆有 writeToFile: atomically
方法阅酪,但余曾多次嘗試[NSMutableArray writeToFile:filePath atomically:YES];
, 然得者皆為fail旨袒。 后發(fā)現(xiàn)NSData的寫入可行,且兩者之間可互相轉(zhuǎn)換遮斥,但轉(zhuǎn)換之法頗為麻煩峦失,于是記錄之,以便日后查詢术吗。
-
NSData 存儲(chǔ)與讀取
NSData 存儲(chǔ)至文件方法:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:someData];
[data writeToFile:writePath atomically:YES];
文件讀取至NSData方法:
NSData *someData = [[NSData alloc]initWithContentsOfFile:writePath];
-
NSData To NSMutableArray
從NSData中解壓出數(shù)組數(shù)據(jù):
NSMutableArray *array= [NSKeyedUnarchiver unarchiveObjectWithData:someData];
-
NSMutableArray To NSData
把數(shù)組數(shù)據(jù)壓縮至NSData:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
-
Decoder & Coder
如果僅僅是按照上述方式是不能解決問題的尉辑,我們需要一點(diǎn)處理技巧。而這個(gè)技巧就是 NSCoder
君较屿。
當(dāng)NSKeyedUnarchiver
和NSKeyedArchiver
在進(jìn)行解壓縮和壓縮時(shí)隧魄,其實(shí)會(huì)調(diào)用到
*數(shù)組中所包含的類 *
*數(shù)組中所包含的類 *
*數(shù)組中所包含的類 *
(重要的事情說三遍)
中的兩個(gè)函數(shù):- (id)initWithCoder:(NSCoder *)aDecoder
和 - (void)encodeWithCoder:(NSCoder *)aCoder
, 假設(shè)你數(shù)組中說包含的類類名是叫aClass
,aClass
中包含了兩個(gè)變量aImportantString
和aMoreImportantString
那么我們就要在這個(gè)aClass中實(shí)現(xiàn)這兩個(gè)方法,并對這兩個(gè)變量進(jìn)行編解碼:
static NSString *aImportantStringKey = @"key1";
static NSString *aMoreImportantStringKey = @"key2";
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
_aImportantString = [aDecoder decodeObjectForKey:aImportantStringKey];
_aMoreImportantString = [aDecoder decodeObjectForKey:aMoreImportantStringKey];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_aImportantString forKey:aImportantStringKey];
[aCoder encodeObject:_aMoreImportantString forKey:aMoreImportantStringKey];
}
-
如何存儲(chǔ)至文件隘蝎?
其實(shí)购啄,這個(gè)問題只要入了門都知道,iOS沙盒的機(jī)制只允許我們在應(yīng)用的Documents目錄下進(jìn)行文件數(shù)據(jù)的存儲(chǔ)嘱么,于是我們需要從bundle中copy或者創(chuàng)建我們的存儲(chǔ)文件狮含,如下:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);NSString * documentDirectory = [paths objectAtIndex:0];
NSString *writePath = [documentDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
//判斷文件是否存在
if (![fileManager fileExistsAtPath:writePath]){
//create the file
[fileManager createFileAtPath:writePath contents:nil attributes:nil];
}else {
//read the data
NSData *someData = [[NSData alloc]initWithContentsOfFile:writePath];
NSMutableArray *array= [NSKeyedUnarchiver unarchiveObjectWithData:someData];
}
-
結(jié)語
以上將數(shù)據(jù)序列化為Data存儲(chǔ)的方法不僅使用于NSMutableArray類或Array類,其它數(shù)據(jù)類型也適用。因?yàn)橹岸啻卧嚵薔SMutableArray寫入不成功(如果是我寫法有問題的話几迄,請知情者指出蔚龙,感激不盡!)映胁,所以記錄之木羹,希望后來者不要犯同樣的錯(cuò)誤。