Proper usage of Application Delegate to send messages
I have a class that communicates with a server (let's call it 'Downloader')开发者_StackOverflow. Sometimes, the server may reject the connection due to a bad login. Instances of this class are used thru-out my program by many different objects, and when the login is rejected Downloader needs to tell the RootViewController to display a login interface. Many of the classes that utilize an instance of Downloader don't have a reference to the RootViewController, so I am sending the message through my application delegate (which has a reference to RootViewController), like so:
[[[UIApplication sharedApplication] delegate] loginFailed];
The application delegate then tells the rootViewController to display the login interface. My question is this: is this the best or 'proper' way to do this? It works, but I am trying to stick to coding conventions. Is there a better way?
This is a good time to use Notifications.
You can have the app delegate (or any class) subscribe to a specific named notification letting it know login has failed, and pull up the login sheet. The background downloader just has to post the notification and then it doesn't care what happens after that. None of the classes in the middle have to ever know anything happened (except they are not going to get data they asked for).
Here's a really simple overview of the calls:
http://mac-objective-c.blogspot.com/2009/02/nsnotifications-broadcasting-mechanism.html
Your method is pretty common and correct. I find if you are doing this often you might want to add a helper method like this:
// in your <myappdelegateclassname>.h
+(void)loginFailed;
// in your <myappdelegateclassname>.m
+(void)loginFailed
{
[[[UIApplication sharedApplication] delegate] loginFailed];
}
Then anywhere in your app you can use:
[<myappdelegateclassname> loginFailed];
Just replace all the names above with your class names.
You might want to create a Singleton class for this purpose. The App Delegate can be used, but it will clutter up your app. Here is an excellent article on singletons, which also discusses the cons of using the app delegate for this purpose:
http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html
精彩评论