Question

Is it ok to read a value stored in NSUserDefaults from multiple views or you only read it once and then you use another method to pass the data to different part of your app?

In other words I want to know if I’m doing it right, what I’m currently doing in an app I’m working on is basically saving a couple of NSIntegers and NSStrings (only two or three of each) in NSUserDefaults and then I’m reading those values in different parts of my app (different views) but I was wondering if this is a common practice or should I be doing something different like, read the value somewhere in the app and then try to use a different method to pass that data to other views. I want to learn best programming practices, that’s all.

What is the most common practice when using NSUserDefaults values in multiple parts of your app?

FYI, I’m familiar with multiple ways to pass data between view controllers such as, delegation, prepareForSegue etc.

Thanks a lot.

Was it helpful?

Solution 2

It is ok to read and even write values to NSUserDefault in multiple places, but it is a better practice to have a global mechanism (like a singleton pattern) to read and write to UserDefaults. this way you'll be guaranteed to have fully synchronized values. all you need to do is to create a new class and add a few Class methods to read and write values from NSUserDefaults.

OTHER TIPS

I would also recommend, to read it multiple times and do not introduce another layer to hold the data. The most important aspect is imo the actuality of the data, which might be changed inbetween different invocations.

It is OK, when you call [NSUserDefaults standardUserDefaults] it will return the same object whether you spread the calls everywhere in the app or you encapsulate the access in a class.

I prefer the later as it allows you to have more readable code (and other benefits):

BOOL hasX = [TLPSettings hasPreferenceX];
if (hasX) {
    [TLPSettings setY:YES];
}

vs

BOOL hasX = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasX"];
if (hasX) {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasY"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

You can change the preferences keys easily (without defining consts for them), change the validation or logic of a preference without messing with it everywhere, debug its usage or rogue values easily, store all or part of them in a different place, etc.

TLP is your three letter prefix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top