I added a custom subview to a UIViewController's content view. From that subview, how can I get a reference to the superview's controller? Thanks
问题:
回答1:
The correct answer is "You're Doing It Wrong™" ;-)
You shouldn't need to reference to a view controller from a view, and you certainly should never retain a view controller in one of your views -- or you'll end up with a retain loop and leak memory.
Cocoa provides multiple patterns to solve this problem:
Use a delegate: Define a protocol called DemoViewDelegate and add a delegate property to DemoView. Then have your view controller implement this protocol. Important: delegates should never be retained! Any delegate property you create should be set to
assign
. See Apple's Delegation docs or just google "delegation pattern".Use the responder chain: Call UIApplication's
sendAction:to:from:forEvent:
and leaveto:
set tonil
to have your action message automatically routed up the responder chain to your view controller. See Apple's Responder docs and the more detailed Action Messages docs.Use a notification: Less common in this particular scenario, but you could also have your view controller listen for a notification, which the view sends.