Search code examples
objective-cdefault-valueclass-variables

In Objective-C, is it possible to set default value for a class variable?


Is there any way to set default values for class properties of a class? Like what we can do in Java, in the constructor of the class eg.-

MyClass(int a, String str){//constructor
  this.a = a;
  this.str = str;
  
  // I am loking for similar way in Obj-C as follows 
  this.x = a*5;
  this.y = 'nothing';
}

Why I am looking for:

I have a class with about 15 properties. When I instantiate the class, I have to set all those variable/properties with some default values. So this makes my code heavy as well complex. If I could set some default values to those instance variables from within that class, that must reduce this code complexity/redundancy.


Solution

  • Write the init, which is doing all the job of full initialization.

    Then just write as many initiators with diferent parameter sets as you need (but think about it: do you really need this or that one?). No, don’t let them do the job. Do them let fill in all the default values (the ones you don’t provide to the message, to this message handling implementatino) and give it all to the first one.

    This first one initator is called designated initator. And be sure not to miss Multiple Initializers and the Designated Initializer. Never ignore the designated one!

    Greetings