简体   繁体   English

将数组的内容写入文本文件

[英]Write contents of array to a text file

I want to write the contents of an array to a text file in my iPhone application. 我想将数组的内容写入我的iPhone应用程序中的文本文件。 I can load the array from the text file but i want to allow deleting of content through the array and again write the contents to the text file. 我可以从文本文件加载数组,但我想允许通过数组删除内容,然后再次将内容写入文本文件。 How can I achieve this? 我该如何实现? Or simply if anyone can guide me how to delete the last word of a text file would also be helpful. 或者,如果有人可以指导我如何删除文本文件的最后一个单词,这也将有所帮助。
EDIT :- basically i want to delete the last word in a text file. 编辑:-基本上我想删除文本文件中的最后一个单词。 can you help me with the logic to achieve that . 你能帮助我实现这个目标的逻辑吗。

Write the contents of your original array as shown below: 编写原始数组的内容,如下所示:

[firstArray writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];

Whenever you want to retrieve and modify the array, retrieve the contents of the file int an NSMutableArray: 每当您要检索和修改数组时,请从NSMutableArray中检索文件的内容:

NSMutableArray *myArr = [NSMutableArray arrayWithContentsOfFile:@"/Users/sample/Untitled.txt"];
[myArr removeLastObject];  //Any modification you wanna do
[myArr writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];

There is method in NSArray to write the array into a file. NSArray中存在将数组写入文件的方法。

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Please check the Apple documentation 请检查Apple文档

the approach in other answers works bu the file is written in a XML format. 其他答案的方法也可以用XML格式编写文件。 to simply write the contents of the array in a text file , I first Appended all the strings of the array into a large string then write that string into the text file .below is the code i used for that 为了简单地将数组的内容写入文本文件,我首先将数组的所有字符串附加到一个大字符串中,然后将该字符串写入文本文件。以下是我用于该代码的代码

NSString *stringToWrite=[[NSString alloc]init];

for (int i=0; i<[stringArray count]; i++)

{
stringToWrite=[stringToWrite stringByAppendingString:[NSString stringWithFormat:@"%@ ",[stringArray objectAtIndex:i]]];

}

[stringToWrite writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

this will write the contents of the array in plain text format. 这将以纯文本格式写入数组的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM