【问题标题】:Reading a plist on the mac在 mac 上读取 plist
【发布时间】:2011-02-02 13:57:59
【问题描述】:

我正在尝试通过读取 plist 来设置图像。我正在开发一个使用当前桌面壁纸并将其设置为 Windows 背景图像的应用程序。文件位于~/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]);

一旦我可以获取位于 plists 字符串中的实际数据,我的计划是将其设置为 NSImageView 或 [window setBackgroundColor:[color]]; 方法

提前致谢。

【问题讨论】:

  • 您保留那本词典有什么原因吗?此外,您应该重命名该变量,因为它包含字典,而不是数据。

标签: cocoa macos plist


【解决方案1】:

请注意,从 10.6 开始,可以通过公共 APIS 获取有关桌面图像的一些信息。阅读NSWorkspace 文档,尤其是-[NSWorkspace desktopImageOptionsForScreen:] 等。

【讨论】:

    【解决方案2】:

    根据我的本地用户帐户的 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"];
    

    【讨论】:

      【解决方案3】:

      plist 是这样的吗?

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

      如果是这样,该代码应该可以工作。但我猜密钥不是第一个字典的根?

      【讨论】:

        【解决方案4】:

        除了现在显示图像外,我一切正常。使用

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

        我能够获得图像的地址。我现在正在尝试设置 windows backgroundColor 这个图像。感谢您在这里的帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-04
          • 2012-10-23
          • 2023-03-17
          • 1970-01-01
          • 1970-01-01
          • 2010-09-27
          相关资源
          最近更新 更多