Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 929
Sadat Avatar asked Jul 19 '10 11:07

Sadat


1 Answers

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.

like image 178
Kurbz Avatar answered Sep 27 '22 01:09

Kurbz