2010-06-21 48 views
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 

希望這有助於!

回答

1

如果你把它放在NSTemporaryDirectory()中,我認爲它應該在應用程序退出時清理 - 這可能值得檢查是否是這種情況。

+0

您仍然應該自己刪除它們:「當您的應用程序確定不再需要時,應該從該目錄中刪除文件。」從[文檔](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

+0

ok thak對所有人。 使用csv的更好的方法是nsfilehandle? 我現在正在檢查此文檔。 – zebra 2010-06-21 16:51:04