您好,我正在尝试从文件加载数据
此函数将数据保存到文档文件夹中的文件
- (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);
}
最佳答案
修正你的答案。这是一个有效的代码,您几乎没有给出文件名。
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"]);
关于Objective-C 保存和加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972955/