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.

 

Leave a Reply

Your email address will not be published.