1

您好我正在尝试从文件加载数据

此功能将数据保存到文档文件夹中的文件中

- (IBAction)saveUser:(id)sender{
   NSString *name = [nameField stringValue];
   NSString *weight = [weightField stringValue];
   NSDate *date = [datePick dateValue];

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

   NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
   [dict setValue:[nameField stringValue] forKey:@"name"];
   [dict setValue:[weightField stringValue] forKey:@"weight"];
   [dict setValue:date forKey:@"date"];
   [dict writeToFile:name atomically:YES];
}

但是,当我尝试加载文件并从中获取数据时,我不能,有人可以告诉我这是如何完成的。


编辑以显示 loadFunction

-(IBAction)loadUser:(id)sender{
 NSString *weight = [weightField stringValue];
 NSDate *date = [datePick dateValue];

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

NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile: name]; 
 NSLog(@"%@", weight);
}
4

2 回答 2

4

修复你的答案。这是一个有效的代码,你几乎没有给出文件名。

NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

在您编写文件的行中:

[dict writeToFile:name atomically:YES];

您必须将名称更改为文件名,像这样

[dict writeToFile:filename atomically:YES];

在您的加载数据方法中:

NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile:filename]; 

NSLog(@"The weight is : %@", [savedData valueForKey:@"weight"]);
于 2012-10-19T11:57:00.120 回答
1

以下似乎符合您的意图(减去代码中的 UI 元素依赖项):

#import <Foundation/Foundation.h>

static NSString *pathToDocuments(void) {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:@"SomeName" forKey:@"name"];
    [dict setValue:@"SomeWeight" forKey:@"weight"];
    [dict setValue:[NSDate date] forKey:@"date"];

    NSString *filePath = [pathToDocuments() stringByAppendingPathComponent:[dict objectForKey:@"name"]];
    [dict writeToFile:filePath atomically:YES];

    [dict release];  dict = nil;

    NSLog(@"%s - Confirming dict is nil: %@",__FUNCTION__,dict);

    dict = [[NSDictionary dictionaryWithContentsOfFile:filePath] mutableCopy];
    NSLog(@"%s - weight = %@",__FUNCTION__,[dict objectForKey:@"weight"] );

    [p release];
}

这会将以下内容打印到控制台:

2012-10-19 06:40:38.691 Untitled[10633:707] main - Confirming dict is nil: (null)
2012-10-19 06:40:38.693 Untitled[10633:707] main - weight = SomeWeight

编辑:

也就是说,我认为问题可能是loadUser...中的文件路径

于 2012-10-19T11:41:55.697 回答