将 CSV 文件保存到文档目录文件夹

Saving CSV file to documents directory folder

我正在编写一个注册应用程序,它应该在文档目录文件夹中保存一个 CSV 文件。我想查看输出,看看在 excel 中打开 CSV 文件时会发生什么。我通过使用以下代码片段找出应该保存的位置导航到文档目录文件夹:

NSLog(@"Info Saved");
NSLog(@"Documents Directory: %@", [[[NSFileManager defaultManager]
                                    URLsForDirectory:NSDocumentDirectory
                                    inDomains:NSUserDomainMask] lastObject]);

这是我的代码,用于保存输入注册表单中 11 个文本字段的信息:

- (IBAction)saveFormButton:(id)sender {

// saves text field data in comma separated CSV file format
NSString *formData = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@\n",
                      self.nameTextfield.text, self.emailTextfield.text,
                      self.phoneTextfield.text, self.termTextfield.text,
                      self.schoolTextfield.text, self.graduationTextfield.text,
                      self.gpaTextfield.text, self.degreeTextfield.text,
                      self.interestTextfield.text, self.groupTextfield.text,
                      self.appliedTextfield.text];

// get document directory path
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                    NSUserDomainMask, YES)objectAtIndex:0];

// append results.csv onto doc path
NSString *event = [documentDirectoryPath stringByAppendingString:@"results.csv"];

// creates folder if it does not exist
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
    [[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}


NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

我是否应该在导航到的特定文件夹中看到文件?

感谢您的帮助,

更改此行:

NSString *event = [documentDirectoryPath stringByAppendingString:@"results.csv"];

至:

NSString *event = [documentDirectoryPath stringByAppendingPathComponent:@"results.csv"];

这可以确保路径格式正确。此外,您似乎在创建文件而不是文件名本身之前检查 "documentDirectoryPath" 是否存在。变化:

if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
    [[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}

至:

if (![[NSFileManager defaultManager] fileExistsAtPath:event]) {
    [[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}

这是一种代码更少的更优雅的方式

 // Content of file
 NSString* str= @"str,hey,so,good";

 // Writing    
 NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:@"file.csv"];
 [str writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];

 // Reading
 NSString *string = [[NSString alloc] initWithContentsOfFile:root encoding:NSUTF8StringEncoding error:nil];

 NSLog(@"%@",string);

结果:

2015-07-15 15:52:56.267 ObjC[2927:15828] str,hey,so,good