您的“资源文件夹”实际上是您的主包的内容,也称为应用程序包。您使用pathForResource:ofType:
或pathForResource:ofType:inDirectory:
来获取资源的完整路径。
如果您想保留一个字符串,则以stringWithContentsOfFile:encoding:error:
方法将一个文件的内容作为字符串加载,该方法对于自动释放的字符串为initWithContentsOfFile:encoding:error:
。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data"
ofType:@"txt"
inDirectory:@"Folder1"];
if (filePath != nil) {
theContents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];
// Do stuff to theContents
}
这与Shirkrin之前给出的答案几乎相同,但是它与目标方法略有不同。这是因为initWithContentsOfFile:
在Mac OS X上已弃用,并且在所有iPhone OS上都不可用。
但在不同的文件夹中有多个具有相同名称的文件夹。所以在这种情况下,如何实现路径 – Rupesh 2009-09-30 08:32:06
@Rupesh:对于您需要使用的第二个文件夹:'[thisBundle pathForResource:@“Data”ofType:@“txt”inDirectory:@“Folder3/Folder1”]'。注意'inDirectory:'参数是相对于捆绑根目录的。 – PeyloW 2009-09-30 08:53:12
你应该真的使用'[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]',这样内存就是_“managed”_,更重要的是''initWithContentsOfFile:'从Mac OS X 10.4开始已经被弃用了,**可在iPhone OS **上使用。所以代码只能在模拟器中工作。 – PeyloW 2009-09-30 08:58:16