Objective-C中的构造函数

23

我已经创建了我的iPhone应用程序,但是我遇到了一个问题。 我有一个classViewController,在其中实现了我的程序。 我必须分配3个NSMutableArray,但我不想在图形方法中这样做。 是否有像Java中的构造函数一样的东西可以在我的类中使用?

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

arrayPosition = [[NSMutableArray alloc] init];
currentPositionName = [NSString stringWithFormat:@"noPosition"];
2个回答

48

是的,有一个初始化器。它叫做-init,它的代码大致如下:

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

编辑:不要忘记-dealloc

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

顺便提一下,在代码中使用本地语言通常是不明智的,你通常应该坚持使用英语,特别是在在线寻求帮助等情况下。


13
@Lohoris: 这条回复是在 ARC 出现之前写的。我猜想在使用 ARC 的情况下,您根本不需要 -dealloc 方法,但建议查阅文档确认一下。 - Williham Totland

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

2
所有的初始化方法都应该调用指定的类初始化方法,你只需要调用一个super init。 - Firo
同意@Firo的观点,你的-init应该像这样:return [self initWithName:nil andAge:0];或者使用其他适当的默认值。 - Tricertops

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接