Beginner OC, this method of Init is not very well understood. Let's now rewrite and customize the Init method to deepen our understanding of him. This example also uses the person class to test.
(i) rewrite the Init method.
(1) Declare the Init method in Person.h:
-(instancetype) init;
(2) Declare member variables in PERSON.M, and write a function that prints member variables, and override the Init initialization method: In the overridden method, the member variable is assigned a value. Note that this init method is a parameterless method.
{ nsstring *_peoplename; int _peopleage;} -(void) show{ NSLog (@ "_peoplename =%@", _peoplename); NSLog (@ "_peopleage =%d", _peopleage);} overriding initialization method;-(instancetype) init{self = [super init]; if (self) { [email protected] "Bob"; _peopleage=24; } return self;}
(3) The overridden Init method is called in MAIN.M and the value of the member variable is printed.
People *people = [[People alloc]init]; [People show];
(4) The output results are as follows:
。
(5) Result analysis, the output result prints out the value that we assign to the member variable when the Init method is defined. Meet expectations. We successfully implemented the rewrite of the Init method.
(ii) Custom Init method.
(1) in the rewritten Init method, we find a problem where we cannot implement the operation of Init in main.m, nor can we implement the assignment of a member variable by the way of parameter passing value. The most deadly problem is the inability to assign a value to a member variable that he owns when instantiating an object. So we'd better customize the Init method.
The custom Init method is declared first in Person.h, and the parameters include Peoplename,peoplename.
-(Instancetype) Initpeople: (NSString *) peoplename andage: (int) peopleage;
(2) Implement the Init method in PERSON.M. Assign a value to a member variable using the passed-in parameter value:
-(Instancetype) Initpeople: (NSString *) peoplename andage: (int) peopleage{self = [super init]; if (self) { _peoplename = peoplename; _peopleage = Peopleage; } return self;}
(3) Instantiate an object in MAIN.M, assign a member variable at the same time as the object is instantiated, and then print the information:
People *people2 = [[People alloc]initpeople:@ "Jack" andage:26];
[People2 show];
(4) Output result:
。
(5) Result analysis, we succeeded in instantiating the object and assigning value to it, this is the function of the initialization method. More flexible than the original rewrite Init method. This has a similar effect to the construction method in C + +.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Objective-c Learning Notes (22)--initialization method Init overrides and customizations