Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone Objective-C中的构造函数_Iphone_Objective C_Constructor - Fatal编程技术网

Iphone Objective-C中的构造函数

Iphone Objective-C中的构造函数,iphone,objective-c,constructor,Iphone,Objective C,Constructor,我已经创建了我的iPhone应用程序,但我有一个问题。 我有一个classViewController,在那里我实现了我的程序。 我必须分配3NSMutableArray,但我不想在Graphich方法中这样做。 我的类没有像Java这样的构造函数吗 // I want put it in a method like constructor java arrayPosition = [[NSMutableArray alloc] init]; currentPositionName = [NS

我已经创建了我的iPhone应用程序,但我有一个问题。 我有一个
classViewController
,在那里我实现了我的程序。 我必须分配3
NSMutableArray
,但我不想在Graphich方法中这样做。 我的类没有像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;
}
编辑:别忘了
-dealoc
,tho'

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

顺便说一句,在代码中使用母语通常是一个糟糕的举动,你通常希望坚持使用英语,尤其是在网上寻求帮助之类的时候。

@Lohoris:这个回答是在ARC成为一件事之前写的。我猜使用ARC您根本不需要
-dealloc
,但您可能需要检查文档。所有init都应该调用指定初始值设定项的类,您应该只有一个超级init调用。同意@Firo,您的
-init
应该如下所示:
返回[self initWithName:nil andAge:0]或任何其他适当的默认值。
/****************************************************************/
- (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;
}