Xcode iPhone:从 .txt 文件中删除文本
我有一个包含一些字符串的文本文件,我可以使用 [NSString initWithContentsOfFile] 函数访问文件中的文本,但接下来我想要做的是从该文件中删除整个文本,但将文本文件保留为我的应用程序将继续将消息字符串输入到文件中。我已经浏览过 NSString、NSStream、NSScanner、NSFileManager、NSHandle 但仍然不知道该怎么做。
我可以执行删除文件功能,但我真的不想这样做,因为我的应用程序需要循环数千次,而且我认为连续删除和创建文件是不明智的。
有什么想法吗?谢谢
I have a text file with some strings in it, I am able to access the text from the file by using [NSString initWithContentsOfFile] function but what I want to do next is remove the whole text from that file but leaving the text file there as my application will continue to feed strings of message into the file. I've looked through NSString, NSStream, NSScanner, NSFileManager, NSHandle but still have no idea how to do it.
I can do a remove file function but I don't really want to do it because my application would be required to loop thousand over times and I think its unwise to continously delete and create a file.
Any idea? thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必从文件中删除内容。当您准备好将新信息放入文件时 - 您将覆盖旧文件。
当您附加附加数据时:
You don't have to remove contents from file. When you will ready to put new information into file - you will just overwrite your old file.
When you are appending additional data:
从文件中删除内容就是重新写入整个文件。
Remove content from a file is to write whole file again.
您是否考虑过使用 NSPipe 来代替?听起来您正在尝试实现一个需要处理的字符串队列。有很多方法可以做到这一点。考虑到 NSOperationQueue、NSNotificationCenter 等其他选项,不确定对文件系统进行颠簸是否是最佳方法。您还可以使用
NSMutableArray
像队列一样使用 addObject: 来推送和removeObjectAtIndex: 来弹出字符串。如果您需要保存未处理的字符串,可以很容易地将数组保存到文件中,作为挂起/终止处理和启动时重新加载的一部分Have you considered using NSPipe instead? It sounds like you are trying to implement a queue of strings that need to be processed. There are many ways to do this. Not sure that thrashing the file system is the best approach given other options like NSOperationQueue, NSNotificationCenter. You can also use
NSMutableArray
like a queue using addObject: to push and removeObjectAtIndex: to pop strings. If you need to save unprocessed strings, it is very easy to save the array to a file as part of your suspend/terminate handling and reload on startup