Search code examples
plistmacruby

MacRuby: How to read a plist file?


I bet this is super simple and easy but can't find a basic example online. How can I read data from a plist file in my project using MacRuby?

Solution:

Turns out there's a few different ways to do it, but the cleanest I've found (so far) is to use the MacRuby helper method load_plist (which turns a plist file's contents into a hash). Also, if you're using XCode, you will need to get the file path relative to your app bundle:

# there's an AppConfig.plist file in my app bundle

config_path = NSBundle.mainBundle.pathForResource('AppConfig', ofType: 'plist')
@config = load_plist File.read(config_path)

Solution

  • This slide deck about MacRuby has some example code for accessing plist files (slides 77-80), the gist of which is that you open the file with NSDictionary.dictionaryWithContentsOfFile and then manipulate it as you would a Ruby Hash, then write it again with writeToFile_atomically. The NSDictionary documentation might be useful to you; you can find it here.