I am using this function to get path of a plist file in my project:
+ (NSString *) appDat开发者_StackOverflowaPath{
NSLog(@"in appDataPath");
NSString *appDPath = nil;
// Get the main bundle for the app.
NSBundle* mainBundle = [NSBundle mainBundle];
if (mainBundle != nil) {
NSLog(@"in appDataPath mainbundle");
appDPath = [mainBundle pathForResource:@"MyAppSettings" ofType:@"plist"];
NSLog(@"appDataPath: %@", appDPath);
}
return appDPath;
}
It goes in if(mainBundle != nil) but appDPath is null. This same function is working in one other project. Why is it not working here? Is there any other way to get path of a plist file in project. Thanks in advance.
Check the case. iOS' filesystem is case sensitive.
Check the file isn't in a directory. You need to call pathForResource:ofType:inDirectory
in that case.
Check the file is enabled for the target you are building. If it isn't, it won't get copied into the bundle.
if by any chance you are having your plist in subfolder, then you should consider using
[[NSBundle mainBundle] pathForResource: ofType: inDirectory:]
by specifying the directory as well.
Try this
+ (NSString *) appDataPath{
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,
NSUserDomainMask,
YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"MyAppSettings.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:@"MyAppSettings"
ofType:@"plist"];
return plistPath;
}
else
// No plist found
}
I am using this code to find plist path in my project.
-(void)CreatePlistPath
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
path = [[documentsDirectory stringByAppendingPathComponent:@"data.plist"] retain];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle =[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
}
精彩评论