2011-12-28 71 views
1

我正在嘗試閱讀〜/ Library/Preferences/com.apple.mail.plist(在Snow Leopard上)以獲取電子郵件地址和其他信息以進入關於對話框。我使用下面的代碼,這顯然是錯誤的:閱讀plist

NSBundle* bundle; 
bundle = [NSBundle mainBundle]; 
NSString *plistPath = [bundle pathForResource:@"~/Library/Preferences/com.apple.mail.plist" ofType:@"plist"]; 
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath]; 
NSString *item = [plistData valueForKeyPath:@"MailAccounts.Item 2.AccountName"];  


NSLog(@"Result = %@", item); 

而且,我需要閱讀的價值是MailAcounts -> Item 2 -> AccountName,我不知道我在做正確此(由於Item 2鍵的空間) 。

我嘗試閱讀蘋果的plist文件開發指南,但沒有幫助。

如何讀取plist並將其作爲NSString提取?

謝謝。

回答

2

第一級是一個數組,所以你需要使用"MailAccounts.AccountName",並把它當作NSArray*

NSString *plistPath = [@"~/Library/Preferences/com.apple.mail.plist" stringByExpandingTildeInPath]; 
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath]; 
NSArray *item = [plistData valueForKeyPath:@"MailAccounts.AccountName"]; 
NSLog(@"Account: %@", [item objectAtIndex:2]); 

或者您可以通過鑰匙去拉離陣列"MailAccounts"首先使用valueForKey:(這將產生NSArray*),然後objectAtIndex:獲得該特定帳戶的字典(如果您需要的不僅僅是名稱,則有用)。

+0

太棒了。感謝您的信息和代碼示例。 –

1

兩件事情:

  1. 你不想要或需要使用NSBundle來獲取文件路徑。該文件位於應用程序包之外。所以你應該只有

    NSString *plistPath = @"~/Library/Preferences/com.apple.mail.plist"; 
    
  2. 你必須展開用戶目錄路徑中的代字號。 NSString有一個這方面的方法。使用類似

    NSString *plistPath = [@"~/Library/Preferences/com.apple.mail.plist" stringByExpandingTildeInPath]; 
    
+0

還行。我得到的只是一個NULL值。 –

+0

好吧,只需通過'「MailAccounts.AccountName」'而不是'「MailAccounts.Item 2.AccountName」'從屬性列表中讀取。唯一的問題是在MailAccounts下有'Item 0'和'Item 1'。它們爲空,因此讀數現在返回NSString爲{null,null,[email protected]}。 –