[英]Write contents of array to a text file
我想將數組的內容寫入我的iPhone應用程序中的文本文件。 我可以從文本文件加載數組,但我想允許通過數組刪除內容,然后再次將內容寫入文本文件。 我該如何實現? 或者,如果有人可以指導我如何刪除文本文件的最后一個單詞,這也將有所幫助。
編輯:-基本上我想刪除文本文件中的最后一個單詞。 你能幫助我實現這個目標的邏輯嗎。
編寫原始數組的內容,如下所示:
[firstArray writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];
每當您要檢索和修改數組時,請從NSMutableArray中檢索文件的內容:
NSMutableArray *myArr = [NSMutableArray arrayWithContentsOfFile:@"/Users/sample/Untitled.txt"];
[myArr removeLastObject]; //Any modification you wanna do
[myArr writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];
其他答案的方法也可以用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];
這將以純文本格式寫入數組的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.