iPhone pathForResource vs bundlePath

时间:2010-06-23 22:00:24

标签: iphone objective-c relative-path nsbundle

我想使用pathForResource,但看起来它不会创建路径(如果不存在)。因此,我试图通过执行以下操作手动创建一个:

 NSString *path = [NSString stringWithFormat:@"%@/%@.plist",[[NSBundle mainBundle] bundlePath],@"myFileName"];

我正在动态创建文件,因此我需要在Build and Run应用程序之后访问它们。但是它将项目放在一个唯一的id文件夹中,所以路径就像:

/Users/RyanJM/Library/Application Support/iPhone Simulator/3.0/Applications/80986747-37FD-49F3-9BA8-41A42AF7A4CB/MyApp.app/myFileName.plist

但每次构建时,该唯一ID都会更改。创建每次都可以到达的路径的正确方法是什么(即使在模拟器中)?

感谢。

更新:编辑了这个问题,希望能够帮助将来遇到它的任何人。

更新:IWasRobbed回答了创建路径URL的正确方法。但我能找到的最佳答案来自Brad Parks。虽然,我确实希望有一种更清洁的方式。

1 个答案:

答案 0 :(得分:1)

根据您提出问题的方式,这是您在构建之前阅读包含在包中的plist的方式:

NSString *propertyListPath = [[NSBundle mainBundle] pathForResource:SomeString ofType:@"plist"];

如果您想要访问每个应用程序所拥有的目录作为您创建AFTER版本的文件的唯一存储区域,请使用以下命令:

#define kFilename   @”data.plist”

- (NSString *)dataFilePath { 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 

return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

然后你可以检查它并在这里进行一些数据处理:

NSString *filePath = [self dataFilePath]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
// do something with data here
}

如果你专门购买/阅读了Beginning iPhone 3 Development第11章,那么他会为你节省很多麻烦,因为他会讨论数据持久性(这是这个例子的来源)。这是一本很棒的书。