NSUserDefaults best practices

Following previous post and observing in many projects how NSUserDefaults settings are handled I have decided to write this NSUserDefaults best practices.

If you look for information about how to set/get any value in the default storage you will get this:

and for getting the value:

Easy, Is not it? The problem appears when there are many attributes deal with with the sets and gets scattered along the code and you want set break points for trapping when this attribute is being accessed.

Proposal

What I propose is to wrap this functionality in a single class that concentrates all the attributes that we want to get/set from the default storage system.

This is the declaration .h:

Its implementation .m:

The class is implemented as a singleton and for each attribute are overwritten set (and get) methods. In that way in a unique place the attribute is set (and get) into (from) the storage system.

And its usage:

The access to the attribute is more clean and in a unique class file we have all the system storage functionality concentrated. You can download the project used for writing this post here.

 

 

 

 

Trap when a class property is set/get

Trap when a class property is set/get

The aim of this post is just explain in a simplified way how to trap when a class property is set/get. The most typical scenario where this mechanism is used is when you have to do some calculations before returning a property value (in case or get) or when you have some tasks when is being set a new property value (in case of set). This mechanism is also very useful when somethings does not go as you expect  with an attribute.

 

The syntax

The syntax is quite straightforward. If I have a property called xxxx, then the methods that you have to overwrite are setXxxx and Xxxx.  It has been added the prefix ‘set’ followed by the first uppercase letter attribute name, ant the rest as it is. Let me show you an example for better understanding, this is the property declaration:

… And those are the overwritten methods:

Let’s play with it

I have created a sample singe view project, and in the ViewController class viewDidLoad method I have added the following chunk:

And this is the log:

You can find the sample project that I have use for writing this post here.