开发者

iphone, write csv file in sandbox

开发者 https://www.devze.com 2023-01-04 09:26 出处:网络
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.

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.

W开发者_如何学Pythonhere 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号