2011-02-02 61 views
3

我試圖通過閱讀plist來設置圖像。我正在研究使用當前桌面壁紙並將其設置爲Windows背景圖像的應用程序。這些文件位於~/Library/Preferences/com.apple.desktop.plist 如何從中讀取密鑰?我試圖閱讀的具體鍵是;在Mac上閱讀plist

NewImageFilePath 
ImageFilePath 

我試過這段代碼,就像在iPhone上閱讀plist,但它沒有工作。

NSString *plistPath = @"~/Library/Preferences/com.apple.desktop.plist"; 
NSDictionary *plistData = [[NSDictionary dictionaryWithContentsOfFile:plistPath] retain]; 
NSString *item = [plistData objectForKey:@"NewImageFilePath"]; 

NSLog([NSString stringWithFormat:@"%@", item]); 

一旦我能得到地處的Plist字符串我的計劃是將其設置爲一個NSImageView或到[window setBackgroundColor:[color]];方法

提前感謝的實際數據。

+0

是否有保留該字典的原因?此外,你應該重命名該變量,因爲它包含一個字典,而不是數據。 – 2011-02-03 17:57:38

回答

0

這個plist是這樣嗎?

<dict> 
    <key>NewImageFilePath</key> 
    <string>...</string> 
</dict> 

如果是這樣,該代碼應該工作。但我猜猜這些鑰匙不是第一個字典的根源?

+0

它看起來像這樣http://cl.ly/4L45 – Frankrockz 2011-02-02 02:34:52

+0

邁克爾在上面的答案中有正確的路徑。 – 2011-02-02 21:48:21

1

根據plist中我的本地用戶帳戶,下面應該爲你做:

NSString *plistPath = @"~/Library/Preferences/com.apple.desktop.plist"; 
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath]; 
NSString *item = [[[plistData objectForKey:@"Background"] objectForKey:@"default"] objectForKey:@"NewImageFilePath"]; 

更簡單的解決方案,以及更容易閱讀,是使用valueForKeyPath:

NSString *plistPath = @"~/Library/Preferences/com.apple.desktop.plist"; 
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath]; 
NSString *item = [plistData valueForKeyPath:@"Background.default.NewImageFilePath"]; 
0

我得到了一切工作,除了現在顯示圖像。使用

NSURL *address = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:[NSScreen mainScreen]]; 

我能夠獲取圖像的地址。我現在試圖設置windows backgroundColor這個圖像。感謝您的幫助。