Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor in Objective-C

Tags:

I have created my iPhone apps but I have a problem. I have a classViewController where I have implemented my program. I must alloc 3 NSMutableArray but I don't want do it in grapich methods. There isn't a constructor like Java for my class?

// I want put it in a method like constructor java  arrayPosition = [[NSMutableArray alloc] init]; currentPositionName = [NSString stringWithFormat:@"noPosition"]; 
like image 584
zp26 Avatar asked May 28 '10 11:05

zp26


People also ask

Does Objective-C have constructors and destructors?

Traditionally in languages like Java and C# a constructor is where you would perform your initializations. In Objective-C you would do so in the init method even though you create a convenience constructor.

What is constructor in C with example?

A Constructor in C is used in the memory management of C++programming. It allows built-in data types like int, float and user-defined data types such as class. Constructor in Object-oriented programming initializes the variable of a user-defined data type. Constructor helps in the creation of an object.

What is init in Objective-C?

Out of the box in Objective-C you can initialize an instance of a class by calling alloc and init on it. // Creating an instance of Party Party *party = [[Party alloc] init]; Alloc allocates memory for the instance, and init gives it's instance variables it's initial values.


2 Answers

Yes, there is an initializer. It's called -init, and it goes a little something like this:

- (id) init {   self = [super init];   if (self != nil) {     // initializations go here.   }   return self; } 

Edit: Don't forget -dealloc, tho'.

- (void)dealloc {   // release owned objects here   [super dealloc]; // pretty important. } 

As a side note, using native language in code is generally a bad move, you usually want to stick to English, particularly when asking for help online and the like.

like image 187
Williham Totland Avatar answered Sep 28 '22 20:09

Williham Totland


/****************************************************************/ - (id) init  {   self = [super init];   if (self) {     // All initializations you need   }   return self; } /******************** Another Constructor ********************************************/ - (id) initWithName: (NSString*) Name {   self = [super init];   if (self) {     // All initializations, for example:     _Name = Name;   }   return self; } /*************************** Another Constructor *************************************/ - (id) initWithName:(NSString*) Name AndAge: (int) Age {   self = [super init];   if (self) {     // All initializations, for example:     _Name = Name;     _Age  =  Age;   }   return self; } 
like image 25
Alex Avatar answered Sep 28 '22 20:09

Alex