为什么init方法以" return self;"结束?而不是"返回0;"?

时间:2013-07-05 20:33:17

标签: 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];
    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

2 个答案:

答案 0 :(得分:6)

因为return 0;会返回NULL指针。不是人们期望成功执行的初始化程序(完全因为它应该返回它已初始化的对象 - 否则你将丢失该对象)。初始值设定项不是main()

答案 1 :(得分:1)

从技术上讲,当你想使用init函数时,就像这样

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

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