为什么我不能在我的项目中获得plist文件的路径?
问题描述:
我使用这个函数来得到在我的项目一个plist文件的路径:为什么我不能在我的项目中获得plist文件的路径?
+ (NSString *) appDataPath{
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;
}
,如果它在(mainBundle =零!),但appDPath为空。这个相同的功能正在另一个项目中工作。为什么它不在这里工作?有没有其他方式可以在项目中获得plist文件的路径。提前致谢。
答
试试这个
+ (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
}
+0
找不到plist。有什么问题?我有plist MyAppSettings.plist资源。我也检查了大小写。 – Piscean
答
我正在使用此代码在我的项目中查找plist路径。
-(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];
}
}
答
检查案例。 iOS的文件系统区分大小写。
检查文件不在目录中。在这种情况下,您需要拨打pathForResource:ofType:inDirectory
。
检查文件是否对您正在构建的目标启用。如果不是,它不会被复制到包中。
答
如果您有在子文件夹您的plist任何机会,那么你应该考虑使用
[[NSBundle mainBundle] pathForResource: ofType: inDirectory:]
通过指定目录中。
在您的项目资源中是否实际存在文件“MyAppSettings.plist”? – DarkDust
是。我的项目资源中有MyAppSettings.plist。 – Piscean