Objective-C保存并加载文件

时间:2012-10-19 11:09:17

标签: objective-c macos cocoa load save

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

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

中的文件
- (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);
}

2 个答案:

答案 0 :(得分: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"]);

答案 1 :(得分: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 ...

中的文件路径