【发布时间】:2014-10-02 13:59:26
【问题描述】:
我正在编写一个将文本保存到 CSV 文件的应用程序。但是在模拟器中试了之后找不到路径下的文件。
代码如下:
#import "protboViewController.h"
@interface protboViewController ()
@end
@implementation protboViewController
@synthesize email;
- (IBAction)retractKeyboard:(id)sender{
[self resignFirstResponder];
}
- (IBAction)saveInfo:(id)sender {
NSString *resultLine=[NSString stringWithFormat:@"%@\n",
self.email.text];
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *mailLista=[docPath stringByAppendingPathComponent:@"elista.csv"];
if (![[NSFileManager defaultManager] fileExistsAtPath:docPath]) {
[[NSFileManager defaultManager] createFileAtPath:mailLista contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:mailLista];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
self.email.text=@"";
NSLog(@"info saved");
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我在控制台中收到“信息已保存”提示,但是当我转到“iPhone Simulator”文件夹并检查没有文件时。
另外,我如何从设备将此文件导出到我的计算机?
提前致谢!
编辑:
现在我让它创建一个文件并添加一行文本,但如果我尝试添加一行文本,整个文件将被替换为带有一行文本的新文件。
#import "protboViewController.h"
@interface protboViewController ()
@end
@implementation protboViewController
@synthesize email;
- (IBAction)retractKeyboard:(id)sender{
[self resignFirstResponder];
}
- (IBAction)saveInfo:(id)sender {
NSString *resultLine=[NSString stringWithFormat:@"%@\n",
self.email.text];
NSArray *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docPath objectAtIndex:0];
NSString *mailLista=[docDirectory stringByAppendingPathComponent:@"elista.csv"];
NSError *csvError = NULL;
BOOL written = [resultLine writeToFile:mailLista atomically:YES encoding:NSUTF8StringEncoding error:&csvError];
if (!written)
NSLog(@"write failed, error=%@", csvError);
else
NSLog(@"Saved! File path =", mailLista);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我搜索了一个答案,发现“由于您没有使用 for 循环,请确保并在您的头文件中声明 outputString。在您的 viewDidLoad 中对其进行初始化,然后您将能够附加到它。”
如何在我的头文件中声明它,我应该在 viewDidLoad 中初始化什么?
再次感谢。
【问题讨论】:
标签: iphone xcode ipad nsfilemanager filehandle