Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/121.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.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
Ios 为什么init方法以“return self;”而不是“return 0;”结尾?_Ios_Objective C - Fatal编程技术网

Ios 为什么init方法以“return self;”而不是“return 0;”结尾?

Ios 为什么init方法以“return self;”而不是“return 0;”结尾?,ios,objective-c,Ios,Objective C,我为什么要放回自己;在类的末尾,而不是返回0;?这两种说法的区别是什么 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { //Call the init method implemented by the superclass self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

我为什么要放回自己;在类的末尾,而不是返回0;?这两种说法的区别是什么

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    //Call the init method implemented by the superclass
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       //Create two arrays and make the pointers point to them
       questions = [[NSMutableArray alloc] init];
       answers = [[NSMutableArray alloc] init];

       //Add questions and answers to the arrays
       [questions addObject:@"What is 7 + 7?"];
       [answers addObject:@"14"];

       [questions addObject:@"What is the capital of Vermont?"];
       [answers addObject:@"Montpelier"];

       [questions addObject:@"From what is cognac made?"];
       [answers addObject:@"Grapes"];

   }

   // Return the address of the new object
   return self;
}

@end

因为返回0;将返回空指针。对于成功执行的初始值设定项来说,这并不是人们所期望的,因为它应该返回它已初始化的对象,否则您将丢失该对象。初始值设定项不是main。

从技术上讲,当您想要使用init函数时,应该是这样的

MyClass *foo = [[MyClass alloc] initFunction];

因此,如果返回0,对象foo将无法访问新创建的MyClass。

顺便问一下:为什么类以返回self结尾;-并不是以return self;结尾的类;。该类以@end结尾。你说的是一种方法。H2CO3的评论:修复格式-if块缩进错误。作为objective-c的新手,但有一些编码经验,我有一个确切的问题。我认为这个问题的问题在于作者没有确定他们对语言的熟悉程度。init方法通常是实例方法,而不是类方法。因此,如果返回0,则对象foo无法访问新创建的MyClass。不知道你这是什么意思。我可以轻松地向id0发送消息,就像向带有isa指针甚至对象的结构发送消息一样。从-init返回0表示alloc失败,这可能与您为使alloc失败所做的任何努力相比。@CodaFi:它也可能表示初始化失败-因此著名的if self=[super init]。