In object c, is it possible to set a default value for a class variable?

I searched ans in stackoverflow and google but didn't get what I needed.

What I'm looking for:

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

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 am I looking for:

I have a class with 15 properties. When I create an instance of the class, I have to set all these variables / properties with some default values. Thus, this makes my code heavy as well as complicated. If I could set some default values ​​for these instance variables from this class, this should reduce this code complexity / redundancy.

I need your help.

Thanks in advance for your help.

-Sadat

+5
3

init, .

, ( : ?). , . , (, , ) .

. . !

+3

,

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

, MyClass *instance = [[MyClass alloc] init], ivars.

, , .

+4

In the class interface:

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

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

@end

Then in 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;
}

( NSIntegeris a typedef for intor long, depending on architecture.)

+1
source

All Articles