我有一个NSMutableDictionary,我用
编写了它[stuff writeToFile:@"TEST" atomically:YES];
我将来如何检索它?
另外,如果我决定用4S替换我的iPhone 4,会发生什么?我的作品可以转移吗?
答案 0 :(得分:9)
我想你想要这样的东西:
[[NSMutableDictionary alloc] initWithContentsofFile:[self dataFilePath]];
您需要获得存储和检索文件的正确路径,按照以下惯例:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"TEST"];
}
答案 1 :(得分:2)
首先,您需要定义要写入的路径。如果您在iPhone模拟器中使用[stuff writeToFile:@"TEST" atomically:YES];
,它将在您Mac的主目录中编写一个名为TEST的文件。使用此代码保存到模拟器和iPhone上的Documents文件夹
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
以下是读取和写入文件所需的代码。
-(void)writeFileToDisk:(id)stuff
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = @"TEST";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
[stuff writeToFile:fileAndPath atomically:YES];
}
-(void)readFileFromDisk
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = @"TEST";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
NSArray *stuff = [[NSArray alloc] initWithContentsOfFile:fileAndPath];
NSLog(@"%@",stuff);
[stuff release];
}
答案 2 :(得分:0)
您可以使用NSUserDefaults来存储您的词典,如下所示:
[[NSUserDefalts standardUserDefaults] setObject:myDictionary forKey:@"myKey"];
之后您可以像这样检索它:
[[NSUserDefalts standardUserDefaults] objectForKey:@"myKey"];
如果您在iPhone 4或iPhone 4S上使用相同的代码,也不会发生任何事情。
答案 3 :(得分:0)
Swift解决方案
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePath = (documentsPath as NSString).stringByAppendingPathComponent("data.txt")
if let data = NSDictionary(contentsOfFile: filePath) {
}