在应用程序启动时获取包文件引用/path

假设我有一个包含在主应用程序包中的任意文件集。 我想获取启动时的文件URL并将其存储在某处。 这可能使用NSFileManager ? 这方面的文件不清楚。

注:我只需要文件的URL,我不需要访问实际的文件。

您可以使用主包中的文件的URL

 NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeFile" ofType:@"jpeg"]; NSURL *url = [NSURL fileURLWithPath:path]; 

您可以将此URL写入(例如)Documents目录中的属性列表文件:

 NSString *docsDir = [NSSearchForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Files.plist"]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[url absoluteString] forKey:@"SomeFile.jpeg"]; [dict writeToFile:plistPath atomically:YES]; 

如果您不知道文件的名称,而您只想列出该文件夹中的所有文件,请使用

 NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] bundlePath] error:NULL]; for (NSString *fileName in files) { NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil]; NSURL *url = [NSURL fileURLWithPath:path]; // do something with `url` } 

是的,你会得到他们的path:

 NSString *path = [NSBundle mainBundle] pathForResource:@"file1" ofType:@"png"]; NSURL *fileURL = [NSURL fileURLWithPath:path] // save it as any other object or in a dictionary: [myMutableDictionary setObject:fileURL forKey:@"file1.png"]; 

编辑:获取文件的完整列表,使用NSFileManager,获取捆绑包本身的path,然后走每个目录获取文件,制作url,并将其保存在某个地方。 因此,如何走一个目录来做到这一点代码。 [你应该更新你的问题,以更具体的你想要什么,这是根本不明确]

在10.6或iOS 4上有NSBundle ( 文档 )上的API可以直接获取NSURL ,而不是传递一个path到NSURL构造函数:

 - (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext; 

它也有一些subdirectorylocalizationName变体,和-pathForResource:等价。