views:

63

answers:

3

I have searched for the ans in stackoverflow and google too, but didnt get what i need.

What I am looking for:

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.

I need your assistance.

Thanks in advance for your help.

-Sadat

+1  A: 

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.)

Wevah
thanks @wevan. still i have to send some params to the initialization method. is there any way to use init{} or something like this without any param?
Sadat
+2  A: 

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.

Kurbz
+1  A: 

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 http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html#//apple_ref/doc/uid/TP30001163-CH22-106376 Never ignore the designated one!

Greetings

Objective Interested Person