2013-08-19 33 views
1

我有一個plist文件,我剛剛創建了字符串;它看起來像這樣:爲什麼我不能檢索我的plist文件?

image of my plist file

這是我用來創建路徑文件的代碼:

NSError *error; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // Create a list of paths 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get a path to your documents directory from the list 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"NailServices.plist"]; // Create a full file path 

NSFileManager *fileManager = [NSFileManager defaultManager]; 

if (![fileManager fileExistsAtPath: path]) { // Check if file exists 
    // Get a path to the plist created before in bundle directory (by Xcode) 
    NSString *bundle = [[NSBundle mainBundle] pathForResource: @"NailServices" ofType: @"plist"]; 
    [fileManager copyItemAtPath:bundle toPath: path error:&error]; // Copy this plist to your documents directory 
} 

這是我使用的檢查數據的代碼(確保這是工作)......我得到一個(空),回從NSLog的語句)

//Load Dictionary with wood name cross refference values for image name 
NSString *plistDataPath = [[NSBundle mainBundle] pathForResource:@"NailServices" ofType:@"plist"]; 
NSDictionary *NailServicesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistDataPath]; 

NSLog(@"\nnailServicesDict: %@", NailServicesDictionary); 

這是我在創建/使用「字符串」 plist文件第一次嘗試;我已經閱讀了我在Google和SO上可以找到的所有內容,但沒有找到一個普通的ol字符串文件的例子。我還需要做些什麼來獲得這個plist數據?

+0

那麼首先,你的plist文件是一個數組,而不是一個字典。嘗試將'NSDictionary'更改爲'NSArray'。 – Jsdodgers

+0

RATS!這是在以下情況下會發生的情況:a)您複製代碼和b)我沒有注意,因爲它是午睡時間!非常感謝你......我現在不在這條路上......:D 請您將您的評論更改爲答案,以便我可以接受它嗎? – SpokaneDude

+0

好的,我把它作爲一個答案加了一點解釋。 – Jsdodgers

回答

1

作爲發表評論者,plist文件可以具有NSArrayNSDictionary作爲其根。您的示例plist的根目錄爲NSArray,因此您需要allocinitNSArray,而不是NSDictionary。如果在Xcode中構建應用程序時將plist存儲在應用程序包中,並且無需在運行時對其進行修改,則無需將其複製到NSDocumentsDirectory。另外,我建議使用[paths lastObject];而不是[paths objectAtIndex:0];,如果paths數組爲空,可能會引發異常。

+0

空閒:當數據更新結束時,應用程序可能會修改plist。謝謝您的回答。 – SpokaneDude

+0

我向Idles提出了一些觀點,因爲他建議使用[paths lastObject],因爲這是我甚至沒有想過的事情,因爲它是plists的第一個定時器。謝謝你們倆。 – SpokaneDude

2

你的問題是你正在創建一個NSDictionary而你的plist是一個NSArray。因此,當您嘗試將其創建爲字典時,它將返回nil,因爲不存在任何字典。

你需要改變:

NSDictionary *NailServicesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistDataPath]; 

NSArray *NailServicesArray = [[NSArray alloc] initWithContentsOfFile:plistDataPath]; 
相關問題