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

Sadat picture Sadat · Jul 19, 2010 · Viewed 7.5k times · Source

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.

Answer

Kurbz picture Kurbz · Jul 19, 2010

If you don't wanna specify parameters,

- (MyClass *)init {
    if (self = [super init]) {
        a = 4;
        str = @"test";
    }
    return self;
}

Then when you do MyClass *instance = [[MyClass alloc] init], it'll set the default values for the ivars.

But I don't see why you posted the constructor with parameters but you don't want to use them.