2012-01-06 68 views
1

我想在我的iPhone应用程序中将数组的内容写入文本文件。我可以从文本文件加载数组,但我想允许通过数组删除内容,并再次将内容写入文本文件。我怎样才能做到这一点?或者,如果任何人都可以指导我如何删除文本文件的最后一个字也是有帮助的。
编辑: -基本上我想删除文本文件中的最后一个单词。你能帮助我实现这一目标的逻辑吗?将数组的内容写入文本文件

回答

2

其他方法swers works bu该文件是以XML格式编写的。简单地写在文本文件中的数组的内容,我首先附加阵列的所有字符串成一个大的字符串然后写该字符串到文本文件中。下面是我用于该

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]; 

代码这将以纯文本格式写入数组的内容。

2

NSArray中有方法将数组写入文件。

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

请检查Apple documentation

+0

谢谢,帮助一点,但数组是用xml格式写入这里是如何保存<?xml version =“1.0”encoding =“UTF-8”?> <!DOCTYPE plist PUBLIC“ - // Apple// DTD PLIST 1.0 // EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”>



\t 一个
\t two \t three \t
我只想要字符串被写入,我将不得不使用xml解析器吗?它更麻烦,是否有解决方法? – Bonnie 2012-01-06 07:25:18

4

写你原来的数组的内容如下所示:

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

每当要检索和修改数组,检索文件INT的内容NSMutableArray:

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

它以这种格式存储为<?xml version =“1.0”encoding =“UTF-8”?> <!DOCTYPE plist PUBLIC“ - // Apple // DTD PLIST 1.0 // EN”“http:// www .apple.com/DTD的/对propertyList-1.0.dtd “> \t 一个 \t \t \t ' – Bonnie 2012-01-06 07:31:13

+0

@Bonnie,格式正常,答案中的另一个方法以字符串数组的形式读取它。除非你需要该文件为特定格式? – jrturton 2012-01-06 07:35:30

+0

@ jrturton,我需要它为纯文本格式,为了进一步使用它,基本上我想删除文本文件中的最后一个单词。你能帮我实现吗? – Bonnie 2012-01-06 09:11:32

相关问题