Skip to content

Instantly share code, notes, and snippets.

@hboon
Created February 20, 2014 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hboon/9112947 to your computer and use it in GitHub Desktop.
Save hboon/9112947 to your computer and use it in GitHub Desktop.
RubyMotion proc leak
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
@window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
@window.makeKeyAndVisible
vc = UIViewController.new
vc.view.backgroundColor = UIColor.redColor
View.show_in_view(vc.view)
@window.rootViewController = vc
true
end
end
class View < UIView
def self.show_in_view(parent)
v = self.alloc.initWithFrame(parent.bounds)
parent.addSubview(v)
pp = proc {|finished|
#A. This causes a leak
#v.method_with_block do
#end
#B. This is ok
in_a_method_ok(v)
}
#doesn't matter if we have this
pp.weak!
#Must use pp like this to trigger
UIView.animateWithDuration(0.3, animations:lambda {
#don't need anything here
}, completion:pp)
end
def dealloc
p "dealloc #{self}"
super
end
#B This is ok
def self.in_a_method_ok(v)
v.method_with_block do
end
end
def initWithFrame(rect)
super
self.backgroundColor = UIColor.blueColor
btn = UIButton.buttonWithType(UIButtonTypeSystem)
btn.frame = [[10, 100], [300, 19]]
btn.backgroundColor = UIColor.greenColor
btn.setTitle('Tap and expect dealloc called', forState:UIControlStateNormal)
btn.addTarget(self, action:'removeFromSuperview', forControlEvents:UIControlEventTouchUpInside)
addSubview(btn)
self
end
end
class UIView
def method_with_block(&block)
p "called method_with_block"
block.weak!
#A storing a strong reference ref to the block stops self from being released, so the block must be storing a strong reference back to self somehow, even after #weak!
#B It's alright for (B)
@stored_proc = block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment