iphone,在沙盒中写入csv文件

iphone,在沙盒中写入csv文件

问题描述:

我必须写(在应用程序的开始)和删除是内容(在应用程序的结尾)在我的沙箱文件与数据流的csv。

i must write (at start of app) and delete is content (at the end of app) a csv in my sandbox file with a stream of data. For your experience, what's the best way to do this?

编辑:

m尝试:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filename =@"test.csv";
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filename];
if(![[NSFileManager defaultManager] fileExistsAtPath: fullPathToFile]) {
            [[NSFileManager defaultManager] createFileAtPath: fullPathToFile contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: fullPathToFile];
NSString *data = [NSString stringWithFormat:@"%@,%@\n", latitudine.text, longitudine.text];
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];

它工作,但....每次writedata调用我只有一行,没有追加。我想收集我的两个textlabel的所有值。

it work but.... every time writedata is call i got only one row, no append. i want to collect all values of my two textlabel.

我的错误在哪里?

edit2:

yessss,找到含有此代码的解决方案:

yessss, find the solution with this code:

首先我创建了这个:

- (NSString *)dataFilePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:@"myfile.csv"];

}

并在我的viewDidLoad i检查并且如果不存在,创建我的文件

and in my viewDidLoad i check and if does not exist, create my file

if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
    [[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
    NSLog(@"Route creato");

}

并且在我的一个方法中数据并附加到我的文件:

and in one of my method i add the code for retrieve data and append to my file:

NSString *data = [NSString stringWithFormat:@"%@,%@ ", latitudine.text, longitudine.text]; 
//create my data to append
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ]; 
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]]; 
//position handle cursor to the end of file
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];   
//write data to with the right encoding

希望这有帮助!

如果你把它放在NSTemporaryDirectory(),我认为应该在应用程序退出清理 - 这可能值得检查,如果这是

If you put it in NSTemporaryDirectory(), I think it's supposed to be cleaned up on app exit — it's probably worth checking if this is the case.