Database Reference
In-Depth Information
As you can see we start out by getting the
NSUserDefaults
object by calling the class method
standardUserDefaults
on the
NSUserDefaults
class. This method returns the shared defaults object.
Then we call the instance method
stringForKey:
on the
NSUserDefaults
object. There are other
instance methods that you can use to get other object types out of the user defaults store. In our
hasDefaults
method we combine these two lines into one call. Both produce the same output.
Next we need to create a method that will set these user defaults if they do not exist. This method is
important because we want to know that our defaults exist, even if the application is running for the
first time.
- (void)createDefaults {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = @{CTDisplayName:@"John Doe",CTFavoriteNumber:@1};
[userDefaults registerDefaults:appDefaults];
}
We start off by getting our
NSUserDefaults
object as we discussed previously. We then create a dictionary
to hold our key value pairs. Finally, we create those by calling the instance method
registerDefaults:
on
the
NSUserDefaults
object and passing our
appDefaults
dictionary as the parameter.
Our final step is to add our login inside the
application:didFinishLaunchingWithOptions
method of
our application delegate. The first thing we want to do when this method is called is determine whether
our defaults exist. If they don't, then we need to create them. Add these lines at the top of this method:
if(![self hasDefaults])
[self createDefaults];
The first thing we want to do when we launch the app is to determine if our defaults exist by calling the
hasDefaults
method. If they don't then we create them by calling the
createDefaults
method. We are
now done setting up our user defaults. It is necessary to do this because there has to be a default set.
Our application is going to check whether there is one set, so we always know there has been one set.
Main View Controller
Now that we have our constants and our user defaults set up we want to be able to show the user
what those defaults are set to. We display a welcome message using the user's default values.
Let's start by cleaning up some of the default code that was added for us.
In the
MainViewController.h
file remove the import command for the
FlipsideViewController.h
.
Also remove the delegate
FlipsideViewControllerDelegate
adoption.
MainViewController.h
should
now look like this:
#import <CoreData/CoreData.h>
@interface MainViewController : UIViewController
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end
Search WWH ::
Custom Search