2
我必须编写(在应用程序的开始处)并删除内容(在应用程序的结尾处)我的沙盒文件中的csv数据流。 为了您的经验,最好的方法是什么?iphone,在沙盒中写入csv文件
编辑:
我试图用这样的:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename [email protected]"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]];
它的工作,但....每次写数据是叫我只拿到了一排,没有追加。我想收集我的两个文本标签的所有值。
我的错误在哪里?
EDIT2:
yessss,找到这段代码的解决方案:
我第一次创造这一个:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"myfile.csv"];
}
,并在我的viewDidLoad我检查和如果不存在,请创建我的文件
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(@"Route creato");
}
,并在我的方法之一,我添加代码检索数据并添加到我的文件:
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
希望这有助于!
您仍然应该自己删除它们:“当您的应用程序确定不再需要时,应该从该目录中删除文件。”从[文档](http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW12) – progrmr 2010-06-21 15:48:43
ok thak对所有人。 使用csv的更好的方法是nsfilehandle? 我现在正在检查此文档。 – zebra 2010-06-21 16:51:04