views:

67

answers:

1

Hi,

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?

edit:

i'm trying with this:

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

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.

Where my mistake?

edit2:

yessss, find the solution with this code:

first i've create this one:

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

}

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

Hope this helps!

A: 

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.

tc.
You still should remove them yourself: "Your application should remove files from this directory when it determines they are no longer needed." from the [docs](http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW12)
progrmr
ok thak's to all.The better way for working with csv is nsfilehandle?i'm now checking this doc.
zebra