-4

Why would I put "return self;" at the end of the class rather than "return 0;"? What is the difference between the two statements?

- (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
4

2 回答 2

6

Because return 0; would return a NULL pointer. Not something one expects from an initializer that has executed successfully (exactly because it's supposed to return the object it has initialized - else you would have lost the object). Initializers are not main().

于 2013-07-05T20:35:02.510 回答
1

Technically when you want to use an init function, it would be like this

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

So if you return 0, the object foo cannot have access to your newly created MyClass.

于 2013-07-05T20:36:26.190 回答