iPhone pathForResource vs bundlePath

2019-07-30 13:15发布

问题:

I want to use pathForResource, but it doesn't look like it will create the path if one doesn't exist. Therefore I'm trying to create one manually by doing the following:

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

I'm creating files dynamically, so I need to access them after I have Build and Run the application. But it puts the project in a unique id folder so the path comes out to something like:

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

But that unique id changes every time I do a build. What is the proper way to create a path that I can get to every time (even in the Simulator)?

Thanks.

Update: edited the question, hopefully to help anyone who comes across it in the future.

Update: IWasRobbed answered the proper way to get create a path URL. But the the best answer I've been able to find is from Brad Parks. Though, I do wish there was a cleaner way.

回答1:

With the way you phrased your question, this is how you read a plist that has been included in the bundle before build:

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

If you want to access the directories that each app has as a unique storage area for a file that you create AFTER build, you use this:

#define kFilename   @”data.plist”

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

return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

Then you can check for it and do some data handling here:

NSString *filePath = [self dataFilePath]; 

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

You would save yourself a lot of trouble if you bought/read Beginning iPhone 3 Development specifically chapter 11 where he goes over data persistence (which is where this example came from). It's a great book.