I'm just starting with Objective C and xcode. I've been exploring NSUserdefaults.
I can save my text field's input to the plist file. Nad can retrive it to a label when the application launches again.
What I can't do is get an alternative text to show IF the plist key is empty. Using the code below my label is just开发者_JS百科 empty until I add text back to the plist via the text field. Any pointers please?
- (void)viewWillAppear:(BOOL)animated;
{
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
NSString *theNewString=[ud objectForKey:@"textFieldKey"];
// update the label
if (theNewString) {
[mylabel setText:theNewString];
} else {
[mylabel setText:@"nothing stored"];
}
}
Handling the case of a nil string or a valid string of length 0 (empty):
if (theNewString.length > 0) {
[mylabel setText:theNewString];
} else {
[mylabel setText:@"nothing stored"];
}
if (theNewString != nil) {
[mylabel setText:theNewString];
} else {
[mylabel setText:@"nothing stored"];
}
The proper method for NSUserDefaults is to initialize it with default values. The best way to do that is to use the +initialize method of the object, which get´s called before an instance is created:
+ (void)initialize{
// This method may be called more than once when it is subclassed, but it doesn´t matter if user defaults are registered more than once.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Add each initial value to a dictionary
NSDictionary *appDefaults = [NSDictionary
dictionaryWithObject:@"nothing stored" forKey:@"textFieldKey"];
// Then store the dictionary as default values
[defaults registerDefaults:appDefaults];
}
A good programming rule is also to define the keys to prevent typing errors:
#define HSTextFieldKey @"textFieldKey"
精彩评论