开发者

if else statement when no data in plist - NSUserdefaults

开发者 https://www.devze.com 2023-04-12 18:04 出处:网络
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 ag

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"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号