Weak Attribute Accessors in RubyMotion
It’s useful – and crucial – in RubyMotion to define attribute accessors so only a weak reference is held to avoid cyclic redundancies.
You can define a simple DSL:
class Class
def weak_attr_accessor(*my_accessors)
my_accessors.each do |accessor|
define_method(accessor) do
instance_variable_get("@#{accessor}")
end
define_method("#{accessor}=") do |accessor_value|
instance_variable_set("@#{accessor}", WeakRef.new(accessor_value))
end
end
end
end
Then use it like this:
class SomeView < UIView
weak_attr_accessor :view_controller
end
I’m pretty sure I copied (and maybe modified the code a little) from this gist, but it looks like the link doesn’t work anymore.
UPDATE: Exactly 1 year later (no kidding), I finally wrote a weak_attr_accessor because I wanted to use it in purplish-layout.