user440096
user440096

Reputation:

Checking that you NSUserDefaults has valid data

I load my data from NSUserDefaults and it works well.

But I'm a little concerned that the first time the app will be fun and there is no saved data something strange might happen. Is there a way to check that I am not getting back nil values or some kind of standard query to see what you are getting back is a valid answer?

Would putting a

ctCountry.isoCountryName = [prefs objectForKey:@"ctCountry.isoCountryName"];
    if (ctCountry.isoCountryName == nil)
    {
       //code to handle noobject returned
    }

be a valid and solid way to handle this kinda of work?

Current Code. No checks for data validity.

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

ctCountry.isoCountryName = [prefs objectForKey:@"ctCountry.isoCountryName"];
ctCountry.isoCountryCode = [prefs objectForKey:@"ctCountry.isoCountryCode"];
ctCountry.isoDialingCode = [prefs objectForKey:@"ctCountry.isoDialingCode"];

Thanks -Code

Upvotes: 1

Views: 92

Answers (2)

Ole Begemann
Ole Begemann

Reputation: 135540

Yes, checking for nil works. Better yet, you could register default values by passing a dictionary of the default preferences to -[NSUserDefaults registerDefaults] at every app launch.

Upvotes: 2

kennytm
kennytm

Reputation: 523164

Yes. It is not possible to store nil, so the only time ctCountry.isoCountryName == nil is when the corresponding preference does not exist.

Upvotes: 1

Related Questions