I'm writing an iPhone program that has a login view controller that allows the user to login. I have a method I use within that controller that checks the authentication of the username and password. I'm using the keychain to store the username and password, but I'm wondering how I go about communicating outside of the class that the username and password is authentic without duplicating code.
This is probably very 开发者_Go百科simple, but it's getting late and my brain is completely fried...
Good question, and Simon's approach is certainly reasonable.
Another idea would be to create a new class, modeled as a Singleton, called Security and place your authentication method there. Then any object who wishes to validate the user could simply call into Security.
You can read more on the Singleton pattern here: http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/cocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html#//apple_ref/doc/uid/TP40002974-CH6-SW6
Hope this helps.
Andrew
One way would be to move the code for handling storing and checking username/password into your AppDelegate class, then in your view controller classes you can do something like:
MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
// Store password
[appDelegate storePassword:foo forUsername:bar];
// Then later, or in another class...
if ([appDelegate userIsAuthenticated]) {
// Stuff for authenticated users goes here
}
(You'll need to add #import "MyAppDelegate.h"
to the top of the view controller's .m file.)
To better match the MVC paradigm, you should probably move all your password checking and storing code outside of the view controller, and into a state modeling class.
The password model object doesn't particularly need to be a singleton (some app might need multiple passwords, etc.).
When creating the view controller and any other objects than needs to touch the password credentials, pass it a pointer to the new password model object to message for store, verify, etc. That way all your password modeling code will be encapsulated and hidden in one place.
精彩评论