简体   繁体   English

cocoa和objective c保存,编辑和加载文件

[英]cocoa and objective c save, edit and load files

hello I am trying to create a text file that will then store some data 您好我正在尝试创建一个文本文件,然后存储一些数据

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

}

I want to be able to create a file that stores the following information and uses the name field as the name of the file. 我希望能够创建一个存储以下信息的文件,并使用名称字段作为文件的名称。 I also want to be able to load the file and read that data from it 我还希望能够加载文件并从中读取数据

Any help is appreciated Thanking You 感谢任何帮助感谢你

This is quite simple. 这很简单。 But you might want to look into NSMutableDictionary instead. 但您可能希望查看NSMutableDictionary。 Both NSString and Dictionary have methods writeToFile:@"filename.txt". NSString和Dictionary都有方法writeToFile:@“filename.txt”。

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];

you read from the file the same way, 你以同样的方式从文件中读取,

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:name];

As simple as it gets 尽可能简单

I think you may get some informations from class NSFileManager, such as like this, 我想你可能会从类NSFileManager得到一些信息,比如像这样,

[fileManager createFileAtPath:filePath contents:contentData attributes:NULL];

the contentData is NSData, and it includes the content of what you want to save, the filename is in filePath that you need to set. contentData是NSData,它包含您要保存的内容,文件名位于您需要设置的filePath中。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM