iPhone SDK - plist not being copied to simulator
I've created a pList (myData.plist) in XCode & populated it, but when I run the program it's not being copied to the iphone simulator directory. Hence, I can't read from it. I've logged the filename and it appears 开发者_运维百科to be pointing to the correct place, there's just no plist file there (confirmed in Finder)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *pListFileName = [documentsDirectoryPath stringByAppendingPathComponent:@"myData.plist"];
NSLog(pListFileName);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: pListFileName]) {
self.pList = [[NSMutableDictionary alloc] initWithContentsOfFile:pListFileName];
//code for reading data in plist
}
Two things:
- Make sure it's marked to be included in the target's bundle.
Right click on the file in the project navigator in Xcode and choose "Get Info". In the "Targets" tab, make sure the checkbox for your target it checked.
This will make sure the file is copied to into your project's bundle.
- You then have to extract it to the bundle and copy it to your Documents directory when your app is run. If your check to see if the plist is in your documents directory fails, copy it from your bundle.
The code, but without any necessary error checking:
if (![fileManager fileExistsAtPath: pListFileName]) {
//Copy the file from the app bundle.
NSString * defaultPath = [[NSBundle mainBundle] pathForResource:@"myData" ofType:@"plist"];
[fileManager copyItemAtPath:defaultPath toPath:pListFileName error:NULL]
}
self.pList = [[NSMutableDictionary alloc] initWithContentsOfFile:pListFileName];
Again, I removed any error checking, but you should include it in your production code.
精彩评论