目标c中的构造函数

zp2*_*p26 23 iphone constructor objective-c

嗨,我创建了我的iPhone应用程序,但我遇到了问题.我有一个classViewController我实施我的程序的地方.我必须分配3 NSMutableArray但我不想在grapich方法中这样做.我的班级没有像java这样的构造函数?非常感谢,对不起我的英语XP

// I want put it in a method like constructor java

arrayPosition = [[NSMutableArray alloc] init];
currentPositionName = [NSString stringWithFormat:@"noPosition"];
Run Code Online (Sandbox Code Playgroud)

Wil*_*and 48

是的,有一个初始化程序.它被称为-init,它有点像这样:

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

编辑:别忘了-dealloc,你.

- (void)dealloc {
  // release owned objects here
  [super dealloc]; // pretty important.
}
Run Code Online (Sandbox Code Playgroud)

作为旁注,在代码中使用母语通常是一个不好的举动,你通常希望坚持英语,特别是在网上寻求帮助等时.

  • @Lohoris:这个回复是在ARC出现之前写的.我猜你用ARC你根本不需要`-dealloc`,但你可能想检查一下这些文档. (13认同)

小智 5

/****************************************************************/
- (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;
}
Run Code Online (Sandbox Code Playgroud)

  • 所有的inits应该调用指定初始化程序的类,你应该只有一个超级init调用. (2认同)