[MacRuby-devel] Behaviour when local variables pointing to non-auto-retained objects go out of scope?

Michael Johnston lastobelus at mac.com
Tue Jan 5 01:30:05 PST 2010

I just purchased the book Programming Cocoa with Ruby, and am working  
through the examples using Macruby.

This tiny app works fine in rubycocoa, but in macruby the created  
statusbar item immediately disappears.

#!/usr/bin/env macruby
framework 'cocoa'

class App
   def applicationDidFinishLaunching(aNotification)
     statusbar = NSStatusBar.systemStatusBar
     status_item =  

     image = NSImage.alloc.initWithContentsOfFile("stretch.tiff")
     raise "Icon file 'stretch.tiff' is missing." unless image


NSApp.delegate = App.new


I assumed this had to do with garbage collection because in obj C  
status_item would have to be retained, and so I changed "status_item"  
to "@status_item"  and then it works fine.

However while playing around with it I also noticed that if I leave  
status_item as a local var and add a "sleep 1" at the end of  
applicationDidFinishLaunching, it also works fine and the status item  
never disappears.

So now I'm not sure whether there is a bug or not. In general, what is  
the intended behaviour of Macruby with local variables referring to  
objects that would have to be retained in obj C when said variables go  
out of scope?

Michael Johnston
lastobelus at mac.com

More information about the MacRuby-devel mailing list