簡體   English   中英

Objective-C 中的構造函數

[英]Constructor in Objective-C

我已經創建了我的 iPhone 應用程序,但我遇到了問題。 我有一個classViewController ,我在其中實現了我的程序。 我必須分配 3 個NSMutableArray但我不想在 Grapich 方法中這樣做。 我的班級沒有像 Java 這樣的構造函數嗎?

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

arrayPosition = [[NSMutableArray alloc] init];
currentPositionName = [NSString stringWithFormat:@"noPosition"];

是的,有一個初始化程序。 它被稱為-init ,它有點像這樣:

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

編輯:不要忘記-dealloc ,tho'。

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

附帶說明一下,在代碼中使用母語通常是一個糟糕的舉動,您通常希望堅持使用英語,尤其是在在線尋求幫助等時。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM