Breaking Cyclical References in RubyMotion with Proc#weak

I recently wrote a blog post illustrating the memory management limitations in RubyMotion. More specifically, I illustrated how easy it was to introduce cyclical references by creating strongly referenced lambdas where the lambdas implicitly have a strong reference back to self.

Unfortunately, at the time of the blog post, it was not possible to break the cyclical reference. Which meant that doing something as innocuous as…

class MyController
  def viewDidLoad
    @block = lambda {}
  end
end

…caused a cyclical reference that resulted in both objects never being deallocated.

I’m happy to report that the RubyMotion team has addressed this issue in “2.17”:http://hipbyte.myjetbrains.com/youtrack/issue/RM-296 by introducing Proc#weak!, which ensures that a _weak_ reference of self is kept by the lambda, which will guarantee that both the block and self will be deallocated.

The example above only has to be tweaked slightly:

class MyController
  def viewDidLoad
    @block = lambda {}.weak!
  end
end

This change makes it possible to use ReactiveCocoa where signals are derived from self — e.g. observing changes in properties on self.

I predict, that in the not so distant future, RubyMotion apps will find that their heap space will not continually grow in size. :-)