Constructor in Objective-C

泄露秘密 提交于 2019-12-20 11:18:41

问题


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"];

回答1:


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.




回答2:


/****************************************************************/
- (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;
}


来源:https://stackoverflow.com/questions/2928404/constructor-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!