xcode iPod Touch 和 iPhone 中的文档目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1115212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Document Directory in iPod Touch and iPhone
提问by Josh Bradley
I'm designing an application that reads data to the iPod touch/iPhone that is sent to it via multicast sockets with UDP and I need to store it as a file in a document directory. Does that exist on on the iPhone or iPod Touch? I know there is NSFileHandle and NSFileManager, which is what I plan on using, to take care of reading and writing to the file, but I'm not sure where the "My Documents" section of the iPod touch is if you know what I'm saying. I am not familiar with the iPod/iPhone file directory that well yet, so any help is appreciated! Is there some kind of "general" directory that all developers use to store their files in if they have any involved in their application?
我正在设计一个应用程序,该应用程序将数据读取到 iPod touch/iPhone,该数据通过使用 UDP 的多播套接字发送给它,我需要将其作为文件存储在文档目录中。这在 iPhone 或 iPod Touch 上是否存在?我知道有 NSFileHandle 和 NSFileManager,这是我计划使用的,负责读取和写入文件,但我不确定 iPod touch 的“我的文档”部分在哪里,如果你知道我是说。我还不太熟悉 iPod/iPhone 文件目录,因此非常感谢您的帮助!如果所有开发人员参与他们的应用程序,是否有某种“通用”目录可供所有开发人员用来存储他们的文件?
回答by Tim
You should use your application's Documents directory to store persistent files. You can get the path to the directory using this function, which Apple includes in their template for an application using Core Data:
您应该使用应用程序的 Documents 目录来存储持久文件。您可以使用此函数获取目录的路径,Apple 将其包含在使用 Core Data 的应用程序模板中:
/**
Returns the path to the application's documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
回答by macbirdie
More recently, the template for a Core Data application provides code like this:
最近,Core Data 应用程序的模板提供了如下代码:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
If the returned NSArray from NSSearchPathForDirectoriesInDomains is empty, lastObject returns nil, so as a result, the code is shorter and cleaner.
如果 NSSearchPathForDirectoriesInDomains 返回的 NSArray 为空,则 lastObject 返回 nil,因此代码更短更干净。
One thing you should be aware of -- as of iOS 5, you shouldn't put non-user-generated-data to Documents directory. Your app may be rejected. Instead you should think of putting such logs in Caches
directory. To get path of this one, you need to replace NSDocumentDirectory
with NSCachesDirectory
in the above example code.
您应该注意的一件事——从 iOS 5 开始,您不应该将非用户生成的数据放入 Documents 目录。您的应用可能会被拒绝。相反,您应该考虑将此类日志放在Caches
目录中。要获取此路径,您需要替换上面示例代码中的NSDocumentDirectory
with NSCachesDirectory
。