Eliminating class dependencies on your application delegate

Dec 4, 2009   //   by Rob Segal   //   Development  //  No Comments

Ever have the need to call a method inside your app delegate from an arbitrary place in your code?  We’ve had to deal with this issue in a few cases working on our new project.  We’re making use of a UIScrollView instance to give us that popular flick scroll movement that is so popular on the iPhone.  We’ve found that alot of people have been interested in doing the same thing and you can read our blog on that particular challenge here.  We have a UIScrollView instance sitting inside our app delegate and there are certain parts of our code where we need to move that UIScrollView among different layers in Cocos 2D.  To do that we need access to the scroll view instance itself.  That results in code like the following…

myAppDelegate *app = [[UIApplication sharedApplication] delegate];
UIScrollView *appOverlayScrollView  = (UIScrollView *)app.view;
[[app window] sendSubviewToBack:appOverlayScrollView];

This creates a messy dependency between an arbitrary class and the app delegate class.  Wouldn’t it be great if we could send a message to the app delegate and tell it to move the scroll view to the front or back maintaining encapsulation?  Turns out you can indeed do this.  The UIApplication class contains a method called sendAction which is normally used to send an action message identified by a selector to a specified target.  This method can easily be used to call selectors in any object so the above code can be converted to…

[[UIApplication sharedApplication]
to:[[UIApplication sharedApplication] delegate]

The only downside to this approach is that I haven’t found a way to supply arguments along with the selector so you need to be calling a method with no arguments.  If you know of a way around this issue please do let me know.

Leave a comment

Our Games

Latest Tweets