Sadat
Sadat

Reputation: 3501

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.

Upvotes: 6

Views: 8635

Answers (3)

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

Upvotes: 3

Kurbz
Kurbz

Reputation: 11003

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.

Upvotes: 4

Wevah
Wevah

Reputation: 28242

In the class's interface:

@interface YourClass : NSObject {
    NSInteger a;
    NSInteger x;
    NSString  *str;
    NSString  *y;
}

- (id)initWithInteger:(NSInteger)someInteger string:(NSString *)someString;

@end

Then, in the implementation:

- (id)initWithInteger:(NSInteger)someInteger string:(NSString *)someString {
    if (self = [super init]) {
        a = someInteger;
        str = [someString copy];

        x = a * 5;
        y = [@"nothing" retain];
    }

    return self;
}

(NSInteger is a typedef for int or long, depending on the architecture.)

Upvotes: 1

Related Questions