2010-10-13 52 views
18

我正在實現基於Web服務的應用程序。因爲我需要在.plist中添加一個字符串作爲屬性,並且我需要從代碼中獲取.plist中的值。你們能幫我解決嗎?如何添加並從iPhone中的.plist中獲取值sdk

+0

可能的重複[從plist獲取數據到NSMutableArray並將NSMutableArray寫入同一個plist iPhone](http://stackoverflow.com/questions/9193363/getting-data-from-plist-to-nsmutablearray-and-writing-the-nsmutablearray-to-same) – Monolo 2012-07-15 10:22:44

+0

請參閱[此鏈接](http://www.iphoneexamples.com/)。希望這會對你非常有幫助爲你。祝一切順利。 – Warrior 2010-10-13 12:54:45

回答

29

下面是一個代碼示例:

NSString *path = [[NSBundle mainBundle] pathForResource: @"YourPLIST" ofType: @"plist"]; 
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path]; 
id obj = [dict objectForKey: @"YourKey"]; 
+1

嗨我得到了路徑null你能幫我嗎 – sekhar 2010-10-13 17:30:45

+0

你的plist文件必須添加到項目中,然後你必須在上面的代碼中設置它的確切名稱(包括大小寫)。 – jv42 2010-10-14 08:51:27

+0

那麼多層次的plists如何呢? http://i.imgur.com/bWNM3Va.png – 2015-04-20 16:18:56

15
NSBundle* mainBundle = [NSBundle mainBundle];  

// Reads the value of the custom key I added to the Info.plist 
NSString *value = [mainBundle objectForInfoDictionaryKey:@"key"]; 

//Log the value 
NSLog(@"Value = %@", value); 

// Get the value for the "Bundle version" from the Info.plist 
[mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]; 

// Get the bundle identifier 
[mainBundle bundleIdentifier]; 
5
NSURL *url = [[NSBundle mainBundle] URLForResource:@"YOURPLIST" withExtension:@"plist"]; 
NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url]; 

NSLog(@"Here is the Dict %@",playDictionariesArray); 

或者您可以使用下面還

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Sample.plist"]; 
2

從plist得到很簡單。

NSString *path = [[NSBundle mainBundle] pathForResource:@"SaveTags" ofType:@"plist"]; 
if (path) { 
    NSDictionary *root = [NSDictionary dictionaryWithContentsOfFile:path]; 
} 

如果你想要的東西添加到plist中,也許你可以在這裏找到答案: How to write data in plist?

但是,如果你只是想在你節省一些消息應用程序,是NSUserDefaults的更好的方法。

0

你不能這樣做。無論是iOS還是Mac OS,任何Bundle都是隻讀的,只能讀取它,並且不能創建文件,編寫文件或對文件進行任何操作。這是蘋果的安全功能的一部分。你可以使用NSDocumentsDirectory來爲你的應用程序編寫並閱讀你需要的東西

相關問題