【问题标题】:Why can not i get path of plist file in my project?为什么我无法在我的项目中获取 plist 文件的路径?
【发布时间】:2011-09-21 11:48:28
【问题描述】:

我正在使用这个函数来获取我项目中 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;
}

它进入 if(mainBundle != nil) 但 appDPath 为空。同样的功能正在另一个项目中工作。为什么它在这里不起作用?有没有其他方法可以在项目中获取 plist 文件的路径。提前致谢。

【问题讨论】:

  • 你项目的资源中是否真的有一个文件MyAppSettings.plist
  • 是的。我的项目资源中有 MyAppSettings.plist。

标签: iphone objective-c xcode ios4 plist


【解决方案1】:

检查案例。 iOS 的文件系统区分大小写。

检查文件不在目录中。在这种情况下,您需要致电pathForResource:ofType:inDirectory

检查文件是否已为您正在构建的目标启用。如果不是,它不会被复制到包中。

【讨论】:

    【解决方案2】:

    如果您的 plist 有任何机会放在子文件夹中,那么您应该考虑使用

    [[NSBundle mainBundle] pathForResource: ofType: inDirectory:]
    

    也可以指定目录。

    【讨论】:

      【解决方案3】:

      试试这个

      + (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       
      }
      

      【讨论】:

      • 没有找到 plist。有什么问题?我在资源中有 plist MyAppSettings.plist。我也检查了区分大小写。
      【解决方案4】:

      我正在使用此代码在我的项目中查找 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];
          }
      }
      

      【讨论】:

      • 还有一个异常,源路径为nil
      • path 的数据类型为 Nsstring,所以只需在 .h 文件中声明它即可。无需初始化。
      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多