2012-10-28 88 views
0

我想閱讀我的.plist,但我的NSLog等於「(null)」。 這裏是我的代碼:閱讀.plist

NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:@"data.plist"]; 

NSLog(@"%@", [plistDict objectForKey:@"id"]); 

這裏是我的.plist:http://cl.ly/image/2e3P3Q1z2Z1T

回答

2

你的道路是錯誤的。如果你的plist在你的應用程序資源中,那麼你必須使用NSBundle來獲得它的絕對路徑。

NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; 
NSMutableDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path] 
           mutableCopy]; 

如果它在你的應用程序的文件夾,你可以這樣做:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; 
NSString *path = [basePath stringByAppendingPathComponent:@"data.plist"]; 
NSMutableDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy]; 

注意,從plist中加載的字典或陣列始終是一成不變的。你必須創建一個可變副本。

+0

我的plist在_〜/圖書館/應用程序支持/ iPhone模擬器/ iOS /應用程序/ MY-APP/Documents_,但此代碼不起作用,有什麼想法? – user1269586

+0

請參閱[this](http://stackoverflow.com/a/6907432/343340)瞭解如何獲取文檔文件夾路徑。並看到我更新的答案。 – DrummerB

+0

的NSLog等於 「(空)」 再次... 但我的代碼看起來不錯: ' - (無效)viewDidAppear:(BOOL)動畫{ 的NSArray *路徑= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,SUserDomainMask,YES); NSString * basePath =([paths count]> 0)? [paths objectAtIndex:0]:nil; NSString * path = [basePath stringByAppendingPathComponent:@「data-article-itiap.plist」]; NSMutableDictionary * dict = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy]; NSLog(@「%@」,[dict objectForKey:@「id」]); }' – user1269586