2011-09-21 54 views
0

我使用這個函數來得到在我的項目一個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文件的路徑。提前致謝。

+0

在您的項目資源中是否實際存在文件「MyAppSettings.plist」? – DarkDust

+0

是。我的項目資源中有MyAppSettings.plist。 – Piscean

回答

1

試試這個

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

1

我正在使用此代碼在我的項目中查找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]; 
    } 
} 
+0

你沒有初始化路徑。 – Piscean

+0

有一個例外,源路徑爲零 – Piscean

+0

路徑具有數據類型Nsstring,所以只需在.h文件中聲明它。不需要初始化。 – Sonu

2

檢查案例。 iOS的文件系統區分大小寫。

檢查文件不在目錄中。在這種情況下,您需要撥打pathForResource:ofType:inDirectory

檢查文件是否對您正在構建的目標啓用。如果不是,它不會被複制到包中。

2

如果您有在子文件夾您的plist任何機會,那麼你應該考慮使用

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

通過指定目錄中。

相關問題