2013-04-04 120 views
3

我有一個名爲「config.plist」config.plist在xcode中的plist,我試圖檢索註冊網址(鍵:reg),但是當我打印結果時顯示空值?如何從plist中檢索字符串?

這是我的代碼來檢索字符串..請參考我的plist結構圖像。

NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: [[_config objectForKey:@"URL"] objectForKey:@"reg"]]]; 
+0

你在哪裏存儲你的plist文件? – 2013-04-04 05:53:23

+0

更新:它在我的xcode – akh 2013-04-04 06:06:43

+0

什麼是Xcode?這是一個IDE,根本不存儲任何plist。 – 2013-04-04 06:07:38

回答

1

試試這個代碼

NSString *plistFilePath=[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"]; 
NSDictionary *urlDictionary=[[NSDictionary alloc] initWithContentsOfFile:plistFilePath]; 
NSString *urlString=[[urlDictionary objectForKey:@"URL"] valueForKey:@"reg"]; 
2

嘗試

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"config.plist"]; 
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path]; 
NSString *result = [[[dictionary objectForKey:@"Root"] objectForKey:@"URL"]objectForKey:@"reg"]; 

編輯的資源:

NSString *path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"]; 
+0

+1 ...但是你可以使用keypath'來提高可讀性 – 2013-04-04 05:57:19

+0

還是它的空值 – akh 2013-04-04 05:57:49

+0

如果它存儲在文檔中,看看Bhargavi如何編輯我的答案 – 2013-04-04 06:00:01

4
NSString *plist=[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"]; 
NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:plist]; 
NSString *stringValue=dict[@"URL"][@"reg"]; 

編輯:非常重要的,瞭解以下信息:

在上面dict本身就是objectForKey:@"Root"

和I /我們試圖通過[@"Root"][@"URL"][@"reg"]發現這是不存在的。

因此,對於具有namingConventions可讀性(什麼店)應該是:

NSString *plist=[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"]; 
NSDictionary *rootDict=[[NSDictionary alloc] initWithContentsOfFile:plist]; 
NSString *stringValue=dict[@"URL"][@"reg"]; 

或者,甚至

NSString *plist=[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"]; 
NSString *stringValue=[[NSDictionary alloc] initWithContentsOfFile:plist][@"URL"][@"reg"]; 
+0

IT也是空值 – akh 2013-04-04 06:00:38

+0

我看到您的更新...按照Bhargavi在喬治的回答中建議的路徑 – 2013-04-04 06:02:15

+0

這是因爲您評論說它位於文檔目錄中,請查看編輯在頂部 – 2013-04-04 06:02:29

1
NSString *plist=[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"]; 
    NSLog(@"path%@",plist); 
    NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:plist]; 
    NSLog(@"d%@",dict); 
    NSString *stringValue=[[dict objectForKey:@"URL"] valueForKey:@"reg"]; 

這件事適用於me..Thanks您所有幫助

+0

郵寄plist文件給我,如果沒有問題的發送。在個人資料中找到我的郵件ID – 2013-04-04 06:33:47