簡體   English   中英

是否可以將NSMutableArray或NSDictionary數據保存為iOS中的文件?

[英]is it possible to save NSMutableArray or NSDictionary data as file in iOS?

我想將NSMutableArrayNSDictionary保存為永久文件。 然后,我想稍后重新打開該文件。

這可能嗎? 如果是這樣,我該怎么辦?

寫入文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

[myArray writeToFile:filePath atomically:YES];

從文件中讀取

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

myArray = [NSArray arrayWithContentsOfFile:filePath];

如果文件不存在,myArray將為nil。 NSDictionary有類似的方法。 請查看參考資料以了解這些方法的詳細信息。

可能是您可以將Dictionary轉換為JSON數據並將其寫入文件。

NSDictionary *dict = /* the NSDictionary/NSArray you need to write */

NSError *writeError = nil;
NSData* data;
data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&writeError];

if (!writeError) {
    [data writeToFile:filePath atomically:YES];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM