Objective c 如何从使用writeToFile创建的文件加载NSDictionary?
我有一本NSMutableDictionary,我用Objective c 如何从使用writeToFile创建的文件加载NSDictionary?,objective-c,nsdictionary,nsmutabledictionary,Objective C,Nsdictionary,Nsmutabledictionary,我有一本NSMutableDictionary,我用 [stuff writeToFile:@"TEST" atomically:YES]; 我将来如何检索它 另外,如果我决定用4S替换iPhone4,会发生什么?我的一段书面数据可以传输吗?您可以使用以下方式存储词典: [[NSUserDefalts standardUserDefaults] setObject:myDictionary forKey:@"myKey"]; [[NSUserDefalts standardUserDefau
[stuff writeToFile:@"TEST" atomically:YES];
我将来如何检索它
另外,如果我决定用4S替换iPhone4,会发生什么?我的一段书面数据可以传输吗?您可以使用以下方式存储词典:
[[NSUserDefalts standardUserDefaults] setObject:myDictionary forKey:@"myKey"];
[[NSUserDefalts standardUserDefaults] objectForKey:@"myKey"];
稍后,您可以像这样检索它:
[[NSUserDefalts standardUserDefaults] setObject:myDictionary forKey:@"myKey"];
[[NSUserDefalts standardUserDefaults] objectForKey:@"myKey"];
同样,如果您在iPhone 4或iPhone 4S上使用相同的代码,也不会发生任何事情。我想您想要的是:
[[NSMutableDictionary alloc] initWithContentsofFile:[self dataFilePath]];
您确实需要获得正确的路径来存储和检索文件,方法如下:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"TEST"];
}
首先,您需要定义要写入的路径。如果您使用
[stuff writeToFile:@“TEST”原子方式:YES]
在iPhone模拟器中,它将在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];
}
迅速的解决办法
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePath = (documentsPath as NSString).stringByAppendingPathComponent("data.txt")
if let data = NSDictionary(contentsOfFile: filePath) {
}
可能是这样,但我得到了“null”。您正在设置文件的数据路径吗?我假设您已经涵盖了该部分,但是您确实需要为您的文件获取正确的路径。我添加了一些您可以使用的代码。