在Mac上阅读plist文件

3

我正在尝试从plist文件读取图像。 我正在开发一个应用程序,该应用程序使用当前桌面壁纸并将其设置为窗口背景图像。 文件位于〜/ Library / Preferences / com.apple.desktop.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]];方法。

提前感谢。


你保留那个字典有什么原因吗?另外,你应该重新命名那个变量,因为它包含一个字典,而不是数据。 - Peter Hosey
4个回答

2

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

这个plist文件看起来是这样的吗?

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

如果是这样,那段代码应该可以工作。不过我猜想密钥不在第一个字典的根目录下?


0

除了显示图像之外,我已经把所有东西都搞定了。使用

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

我已经成功获取到图片的地址。现在我正试图将窗口的背景颜色设置为这张图片。感谢你的帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接