2012-05-11 38 views
0

我想寫一個csv文件。我手邊有兩個數組 - 一個帶有標題(名稱,數字等),另一個帶有實際值(Jon,123 ...)。使用writeToFile:自動:連續不起作用...爲什麼?

現在,下面兩個步驟之後:

[[titles componentsJoinedByString:@", "] writeToFile:file atomically:YES]; 

[[values componentsJoinedByString:@", "] writeToFile:file atomically:YES]; 

只值陣列被寫入文件。我意識到我可能需要再次打開文件,但是在寫入第一個數組後,我該怎麼做?或者,如果情況不是這樣,我究竟做錯了什麼?

謝謝!

回答

1

第二行實際上是覆蓋您在第一行寫入的文件。解決此問題的一個簡單方法是簡單地將第二個字符串附加到第一個字符串(可能是在創建csv文件之後使用'\ n')並將該字符串寫入您的文件:

NSString *str1 = [[titles componentsJoinedByString:@", "]; 
NSString *str2 = [[values componentsJoinedByString:@", "]; 
NSString *outputStr = [str1 stringByAppendingFormat:@"\n%@", str2]; 
[outputStr writeToFile:file atomically:YES]; 
+0

謝謝:)我知道我失去了一些東西添加其他行。所以總而言之,是不是可以在同一個文件上使用「writeToFile:atomically」兩次? –

0

第二次它替換舊的內容。因此,您可以閱讀舊內容,將舊內容附加到新內容並保存在文件中。

寫第一行

[[titles componentsJoinedByString:@", "] writeToFile:file atomically:YES]; 

,你需要每次

NSString *previousContent = [[NSString alloc] initWithContentsOfFile:file usedEncoding:nil error:nil]; 
NSString *str2 = [[values componentsJoinedByString:@", "]; 
NSString *outputStr = [previousContent stringByAppendingFormat:@"\n%@", str2]; 
[outputStr writeToFile:file atomically:YES];